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();//这就是了
//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继承基础讲解(原型链、借用构造函数、混合模式、原型式继承、寄生式继承、寄生组合式继承)
- [设计模式] JavaScript 之 原型模式 : Object.create 与 prototype
- javascript基础之十一(基于Object.create()实现类的继承)
- JS学习笔记——JavaScript继承的6种方法(原型链、借用构造函数、组合、原型式、寄生式、寄生组合式)
- 谈谈 Object.create ,JS的原型继承
- Javascript 组合继承 原型链继承 寄生继承
- JavaScript继承基础讲解(原型链、借用构造函数、混合模式、原型式继承、寄生式继承、寄生组合式继承)
- 理清javascript中prototype、__proto__、Object、Function的关系,更好地理解原型继承
- javascript中的原型与继承5--寄生混合继承(Parasitic Combination Inheritance)
- JavaScript继承基础讲解,原型链、借用构造函数、混合模式、原型式继承、寄生式继承、寄生组合式继承
- JavaScript继承基础讲解(原型链、借用构造函数、混合模式、原型式继承、寄生式继承、寄生组合式继承)
- JavaScript中的原型和继承详解(图文)
- 【转载】Javascript原型继承-学习笔记
- JavaScript的模块化:封装(闭包),继承(原型) 介绍
- JavaScript寄生组合式继承分析
- javascript:利用Object.create()方法创建对象
- Javascript对象继承(原型继承法)
- javascript 的 继承(六) 之 寄生组合式继承
- javascript 原型链---继承方式怎么实现继承
- JavaScript原型和继承