2010.06.03(2)——— javascript 简写伪类继承
首先,要理解一个概念,就是:
[color=red]当一个函数对象被创建时,Function构造器参数的函数对象会运行类似这样的一些代码:
this.prototype = {constructor: this};
新函数对象被赋予一个prototype属性,其值是一个包含一个constructor属性且属性值为该新函数对象
该prototype对象是存放继承特征的地方。[/color]
一般的伪类继承方式:
这个继承里面有无谓的prototype操作,最好我们能隐藏这些操作,
还记不记得我们上一次写的那个Method方法呢
我们利用它来简化这个过程,
首先 通过method方法来定义一个inherits方法
我们的inherits和method方法都返回this,这将允许我们可以用级联的样式来编程 如下:
这样一句话就可以构造我们的Cat了
[color=red]但是 这种方式的集成有很多缺陷:没有私有环境 所有属性都是公开的 无法访问super的方法等[/color]
醉倒的危害就是,如果我们再调用构造器函数时 忘了再前面加上new前缀,那么this将不会绑定到一个新对象上,this将会被绑定到全局对象上,这样将破坏全局变量,所以最好的方案就是根本不适用new
首先,要理解一个概念,就是:
[color=red]当一个函数对象被创建时,Function构造器参数的函数对象会运行类似这样的一些代码:
this.prototype = {constructor: this};
新函数对象被赋予一个prototype属性,其值是一个包含一个constructor属性且属性值为该新函数对象
该prototype对象是存放继承特征的地方。[/color]
一般的伪类继承方式:
var Mammal = function(name){
this.name = name;
};
Mammal.prototype.get_name = function(){
return this.name;
}
Mammal.prototype.says = function(){
return this.saying || "";
};
var myCat = new Cat('xiaodu');
var says = myCat.says(); //'meow'
var name = myCat.get_name(); // 'meow xiaodu meow'
//在构造一个伪类来继承Mammal,这是通过定义它的
//constructor函数并替换它的prototype为一个Mammal的实例来实现的
var Cat = function(name){
this.name = name;
this.saying = 'meow';
};
//替换Cat.prototype为一个新的Mammal实例
Cat.prototype = new Mammal();
Cat.prototype.get_name = function(){
return this.says() + ' ' + this.name + ' ' + this.says();
}
这个继承里面有无谓的prototype操作,最好我们能隐藏这些操作,
还记不记得我们上一次写的那个Method方法呢
Function.prototype.method = function(name,func){
if(!this.prototype[name]){
this.prototype[name] = func;
}
return this;
}
我们利用它来简化这个过程,
首先 通过method方法来定义一个inherits方法
Function.method('inherits',function(Parent){
this.prototype = new Parent();
return this;
});
我们的inherits和method方法都返回this,这将允许我们可以用级联的样式来编程 如下:
var Cat = function(name){
this.name = name;
this.saying = 'meow';
}.
inherits(Mammal).
method("get_name",function(){
return this.says() + ' ' + this.name + ' ' + this.says();
});
这样一句话就可以构造我们的Cat了
[color=red]但是 这种方式的集成有很多缺陷:没有私有环境 所有属性都是公开的 无法访问super的方法等[/color]
醉倒的危害就是,如果我们再调用构造器函数时 忘了再前面加上new前缀,那么this将不会绑定到一个新对象上,this将会被绑定到全局对象上,这样将破坏全局变量,所以最好的方案就是根本不适用new