gpt4 book ai didi

javascript - javascript中的原型(prototype)链

转载 作者:搜寻专家 更新时间:2023-11-01 05:06:35 25 4
gpt4 key购买 nike

假设我有两个构造函数:

var Person = function(xx,xx,xxx,xxxxxxx) {
//Person initialization
}

var Man = function(xx,xx,xxx,xxx) {
//Man initialization
}

我希望 Man 从 Person 扩展。

以下是我的想法:

给定一个已创建的 Man 对象:

var m=new Man("xx",....);

1) 当访问 m 的属性时,它将在 Man.prototype 中搜索它。

2) 如果没有找到,它应该在Man.prototype.__prop__中找到它。

所以我所做的就是将 Man.prototype.__prop__ 链接到 Person.prototype

我知道这是常见的方式:

function inherit(superClass) {
function F() {}
F.prototype = superClass.prototype;
return new F;
}
Man.prototype=inherit(Person);

但是当我尝试这样做时:

Man.prototype.prototype=Person.prototype.

为什么它不起作用?

最佳答案

听起来您实际上想要将 Man 的实例链接到 Person 的实例,该实例保留在其构造函数中添加的任何属性,在在哪种情况下你可能真的想要这样的东西:

function Person(a, b) {
this.a = a;
this.b = b;
}

function Man() {}
Man.prototype = new Person("val1", "val2");

var m = new Man();
console.log(m.a);

...打印val1

额外的杂文

inherit 的目的是从一个函数创建一个对象,该函数的 prototype 是给定父类(super class)的函数(无需显式使用 new ), 这正是它的作用。因此,以下打印 string:

function Person() {}
Person.prototype.test = "string";

function Man() {}

function inherit(superClass) {
function F() {}
F.prototype = superClass.prototype;
return new F;
}

var t = inherit(Person);
console.log(t.test);

但是您通常希望将返回的对象分配给另一个函数的原型(prototype):

Man.prototype = inherit(Person);

var m = new Man();
console.log(m.test);

...因此 m.test 也打印 string,这意味着使用 Man 创建的对象链接到 Person 原型(prototype))。

请注意 Man.prototype.prototypeundefined 并且——这是重要的部分——也没有意义。函数有原型(prototype)。其他对象(例如 Man.prototype)没有。 prototype 属性在任何其他上下文中都不是神奇的。为随机对象的 prototype 属性赋值并没有做任何特别的事情。这只是另一个属性。

另请注意,我们从 inherit 返回的内容通过其 prototype 链接到 Person,并且无法访问任何添加的属性到 Person实例

关于javascript - javascript中的原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11288660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com