js自定义类,混合的构造函数/原型方式

“混合的构造函数/原型方式”
用构造函数来定义非函数属性,用原型方式定义对象的函数属性,结果所有函数都只创建一次,而每个对象都具有自由的对象属性实例。
 

 function ocar(color){
  this.color = color;
  this.arr = new Array("s");
 }
 ocar.prototype.showColor = function(){
  alert(this.color);
 }
 var car = new ocar("resd");
 car.showColor();
 
二、为类添加新方法:
可以用prototype属性为以有的类定义新的方法:
比如为Array定义一个dequeue()方法
//创建新的方法
Array.prototype.dequeue = function(str){
 this.push(str);
}
var arr = new Array("s");
arr.dequeue("a");
alert(arr.toString());
 
三、重定义已有的方法:
就像给已有类定义新方法一样,也可以重写类的方法。函数名只是指向函数的指针,因此可以轻易的使用它指向别的函数。从写已有方法的时候Function的第一个F要大写
修改本地类toString()方法。
Function.prototype.toString = function(){
 return "重写toString";
}
function sayHi(){
 alert("Hi");
}
alert(sayHi.toString);
 
四、类的继承:
JS类的继承有很多种,这因为JS种的继承机制并不是明确规定的,而是通过模仿实现的,这意味着所有的继承细节并不是完全解释程序处理。所以我们选择一种适合自己的方法就可以了。
一、对象冒充:
   构造函数使用this关键字给所有属性和方法赋值,因为构造类只是一种函数,所以可以使ClassA的构造函数成为ClassB的方法,然后调用它,ClassB就会收到ClassA的构造函数中定义的属性和方法。例如
function oren(name){
 this.name = name;
 this.sayName = function(){
  alert(this.name);
 }
}
function orenB(name,sex){
 this.newfun = oren;
 this.newfun(name);
 delete this.newfun;
 this.sex = sex;
 this.showSex = function(){
  alert(this.sex);
 }
}
var testA = new oren("linan");
testA.sayName();
var testB = new orenB("ln","男");
testB.sayName();
testB.showSex();
所有的新属性和新方法都必须在删除了新方法的代码后定义。否则会覆盖超类的相关属性和方法。
 
二、call()方法:
call()方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作this的对象,其他参都直接传递给函数本身。
function oren(name){
 this.name = name;
 this.sayName = function(){
  alert(this.name);
 }
}
function orenB(name,sex){
 oren.call(this,name);
 this.sex = sex;
 this.getSex = function(){
  alert(this.sex);
 }
}
var test = new oren("ln");
test.sayName();
var testB = new orenB("linan","man");
testB.sayName();
testB.getSex();
 

这是call()方法继承的例子,这里想让oren中的关键字this等于新创建的orenB对象,因此this是第一个参数

posted @ 2015-09-30 11:42  干货库  阅读(2248)  评论(0编辑  收藏  举报