0
点赞
收藏
分享

微信扫一扫

javascript继承的实现方式


随便写写,具体的就不再做过多啰嗦了

1、原型(Prototype),建议自己研究​​原型与闭包​​

var Person = function(){   
this.name = "liyatang";
};
Person.prototype = {
//可以在这里提供Person的基本功能
getName : function(){
return this.name;
}
}

注:Prototype是私有的,在继承关系中需要将父类对象添加到子类的原型

2、call,applay的使用法

function Animal(name) {
this.name = name;
this.showName = function() {
console.log(this.name);
};
}

function Cat(name) {
Animal.call(this, name);
}
<pre name="code" class="javascript">
function Dog(name) {
Animal.apply(this, name);
}

var cat = new Cat("Black Cat"); //call必须是object

var dog = new Dog(["Black Dog"]); //apply必须是array

cat.showName();
dog.showName();

console.log(cat instanceof Animal);
console.log(dog instanceof Animal);

 3、superClass的使用

function Animal(name) {
this.name = name;
this.showName = function() {
alert(this.name);
};
};

function Cat(name) {
this.superClass = Animal;
this.superClass(name);
delete superClass;
}

var cat = new Cat("Black Cat");

cat.showName();

举报

相关推荐

0 条评论