"父类"
function Foo(name){
this.name = name;
}
Foo.prototype.myName = function(){
return this.name;
};
//让Bar继承Foo
function Bar(name, label){
Foo.call(this, name);//如果需要"父类"的变量
this.label = label;
}
//"你不知道的javascript"一书中建议的继承方法,
//这样Bar.prototype._proto_=Foo.prototype
//书中说虽然Bar.prototype=new Foo()也可以,但是会有副作用
//所以在Bar里面会有一句Foo.call(this, name);
//之前在另外一书中看到的方法是Bar.prototype=new Foo(name)
//那这样会一并将name关联到Bar.prototype
Bar.prototype = Object.create(Foo.prototype);
//自己的方法
Bar.prototype.myLabel = function () {
return this.label;
};
var bar = new Bar("a", "b");
//bar既是Bar又是Foo
//a instanceof A :在a整条原型链上是否有指向A.prototype的对象
console.log(bar instanceof Bar);//true
console.log(bar instanceof Foo);//true
console.log(bar.myLabel());//b
console.log(bar.myName());//a
javascript类与继承
最新推荐文章于 2024-06-26 21:45:19 发布