JAVASCRIPT面向对象的程序设计之原型式继承

本文深入探讨了JavaScript中的一种继承方式——原型式继承,介绍了其由来、实现方式及使用场景。通过具体示例展示了如何利用原型式继承创建新对象,并讨论了引用类型属性在继承中的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原型式继承

道格拉斯·克罗克福德在2006年写了一篇文章, 在该文章中介绍了一种实现继承的方法, 即原型式继承。实现如下:

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

使用方式如下:

var person = {
    name : "Nicholas",
    colors : ["red", "blue", "green"]
}
var obj = object(person);
console.log(obj.name);   //"Nicholas"
console.log(obj.colors);  //"red", "blue", "green"

要求就是必须有一个对象作为另一个对象的基础。 和原型链模式类似,原型链模式是用超类的实例对象重写子类的原型对象,而原型式模式则是通过传入的对象重写目标对象的原型对象。

ECMAScript通过新增Object.create()方法规范化了原型式继承。这个方法接收两个参数:一个作为新对象原型的对象和一个为新定义额外属性的对象。在传入一个参数的情况下,Object.create()与object()方法的行为相同。

使用一个参数:

var person = {
    name : "Nicholas",
    friends : ["Shelly", "Court", "Van"]
};

var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Lina";
yetAnotherPerson.friends.push("Barbie");

console.log(person.friends);     //"Shelly", "Court", "Van", "Rob", "Barbie"
console.log(person.name);   //"Nicholas"
console.log(anotherPerson.name);  //"Greg"
console.log(yetAnotherPerson.name);  //"Lina"

输出结果:  因为friends属性时引用数据类型,且person对象是作为anotherPerson对象和yetAnotherPerson对象的原型,所以在anotherPerson对象和yetAnotherPerson对象对friends对象做的修改会体现在person对象的friends上。

使用两个参数:

Object.create方法的第二个参数和Object.defineProperties()方法的第二个参数相同。

var person = {
    name : "Nicholas",
    friends : ["Shelly", "Court", "Van"]
};

var anotherPerson = Object.create(person, {
    name : {
        value : "Greg"
    }
});

console.log(anotherPerson.name);

备注: 例子及截图均来自《JAVASCRIPT高级程序设计:第3版》

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值