Javascript 实现方法继承

最近在了解javascript的继承机制,了解到Javascript的机制是用时复制,继承是原型链继承,现在有种一知半解的感觉,在此记录一下:

每一个构造函数有自己的prototype属性,指向prototype这个对象,prototype这个对象有一个constructor属性,指向这个构造函数,实例的__proto__指向构造函数的prototype:

(我自己画了一张草图)

所以实现一个简单继承很简单:

function Person(){    
    this.name = 'Person';
};
Person.prototype.getName = function(){
    return this.name;
};

var person = new Person();
console.log(person.getName());//Person

如果我们有一个新的构造函数要继承这个方法呢,只需要改变这个构造函数的prototyope的指向:

function Person(){    
    this.name = 'Person';
};
Person.prototype.getName = function(){
    return this.name;
};
var person = new Person();// Person
console.log(person.getName());
var Bar = function() {
    this.name = "Bar";
};
Bar.prototype = person.__proto__;
var bar = new Bar();
console.log(bar.getName());// Bar

这样就实现了方法的继承。

不对的地方希望有人看到能指正ORZ

posted @ 2017-03-20 18:45  lastnigtic  阅读(140)  评论(0编辑  收藏  举报