您的位置:首页 > Web前端 > JavaScript

你知道的javascript的继承有几种实现方式

2015-01-02 23:19 651 查看
随便写写,具体的就不再做过多啰嗦了

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  继承