如何将两个构造函数链接并继承它们作为原型添加到一个对象中?

3
我是一个有用的助手,可以翻译文本。
我正在使用JavaScript中的原型(我是JS新手),并陷入以下JS代码片段:
我创建了两个函数:
第1个函数
function sample1() {
    this.uname = "Andrew";
}

功能 2

function sample2() {
    this.age = 21;
}

我将sample2的属性继承到sample1中,具体如下:
sample1.prototype = sample2; 

到目前为止,一切都很好,我可以看到sample1sample2作为其原型。但是,使用sample1创建一个包含sample2属性的对象时出现了问题。
let test = new sample1;

现在,尝试访问sample1的属性会输出正确的结果。
test.uname;

但是,尝试访问age的输出为undefined
问题:
如何使用test对象访问age属性?
注意:以上是使用Chrome开发者工具-控制台尝试的
谢谢。

1
你需要调用 sample2,因为它是一个函数。继承它没有意义。sample1.prototype = new sample2 可以起作用。 - Jonas Wilms
这只是一种约定,但可以避免很多混淆。如果函数要像类一样使用,则将其首字母大写。例如:Sample1 而不是 sample1 - Keith
@JonasW. 不太对 - 你需要让sample2的原型链与sample1的原型链相关联。 - Alnitak
2个回答

1
你的unameage属性是由构造函数直接在每个实例初始化时创建的。在这里使用原型继承没有意义。只需运行两个构造函数即可:
function sample2() {
    this.age = 21;
}
function sample1() {
    sample2.call(this); // runs the other constructor on this instance
    this.uname = "Andrew";
}

当覆盖方法时,这与super调用非常相似。

我正在使用JavaScript中的原型

还没有 :-) 您的原型对象为空。

I inherited the properties of sample2 to sample1 as follows:

sample1.prototype = sample2; 

哦,你不应该这样做。sample2 是一个函数对象,通常不需要从它继承任何内容。请注意,sample1.prototype 是使用 new sample1 创建的所有实例将继承的内容 - 它们不是函数。你可能正在寻找

sample1.prototype = Object.create(sample2.prototype);

如果您想使用附加到基类原型的方法而不仅仅是直接附加到“this”的简单每个实例属性,则需要使用Object.create() - Alnitak

1
这是在ES5中构建原型链的正确方法。
从你的基类开始:


以编程为相关内容。
// base class definition
function Sample1(name) {
    this.uname = name;
}

// with an example function stored on the prototype
Sample1.prototype.getName = function() {
    return this.uname;
}

然后使用适当的原型链对其进行子类化:

// create the sub-class constructor
function Sample2(name, age) {
    // invokes superclass constructor, passing any params it needs
    Sample1.call(this, name);

    // define subclass per-instance properties
    this.age = age;
}

//
// *** THIS IS THE IMPORTANT BIT ****
//
// create a correctly chained prototype for Sample2
Sample2.prototype = Object.create(Sample1.prototype);

// and then re-associate the correct constructor method
// to assist with debugging, console.log, etc
Sample2.prototype.constructor = Sample2;

// and add methods to it
Sample2.prototype.getAge = function() {
    return this.age;
}

您可以使用您新继承的“类”,保留 HTML,不进行解释。
// pass multiple parameters, and then query the object
var test = new Sample2("Andrew", 21);
console.log(test.getName());
console.log(test.getAge());

// this should show "Sample2"
console.log(Object.getPrototypeOf(test));

// these should both be "true"
console.log(test instanceof Sample2);
console.log(test instanceof Sample1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接