您的位置:首页 > 移动开发 > Objective-C

javascript中的原型与继承4--原型继承Prototypal Inheritance(Object.create)与寄生继承(Parasitic Inheritance)

2017-11-27 11:34 489 查看
在2006年的时候,一个叫做Douglas Crockford的哥们发明了一个新的继承方式,这种方式不需要定义构造函数。他是这么做的

//210页

function object(o) {
function F() {}
F.prototype=o;
return new F();

}

//essentially,object() performs a shadow copy of any object that is passed into it.

var person={
name:"尼古拉斯",
friends:['a','b']

};

var anotherPerson=object(person);

anotherPerson.name='another';

anotherPerson.friends.push('c');

var anotherPerson2=object(person);

anotherPerson2.name='another2';

anotherPerson2.friends.push('c2');

console.log(person.friends);//[ 'a', 'b', 'c', 'c2' ]

有人感觉这种方式很叼,然后ES5就实现了它,增加了一个Object.create()方法,改写上面的例子如下

var anotherPerson=object(person);  改成  var anotherPerson=Object.create(person);

其他的类似改。

Object.create方法还能接受第二个参数,就不说了。

那么如果想在anotherPerson上面加方法怎么办呢,可以这样(叫做寄生继承):

function createAnother(ori) {
var clone=object(ori);
clone.sayHi=function () {
console.log('hi');
};
return clone;

}

anotherPerson.sayHi();//这就是了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 继承
相关文章推荐