如何 link 两个构造函数并将它们作为对象的原型继承?

How to link two constructors and inherit them as prototype to an Object?

我正在 JavaScript 中使用 prototypes(我是 JS 的新手)并坚持使用以下 JS 代码片段:

我创建了两个函数:

函数 1

function sample1() {
    this.uname = "Andrew";
}

函数 2

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

我继承了sample2sample1的属性如下:

sample1.prototype = sample2; 

至此,一切正常,就像我看到 sample1sample2 作为原型一样。但是,问题在于使用 sample1 创建对象,其中包含 sample2.

的 属性
let test = new sample1;

现在,尝试访问 sample1 的 属性 会给出正确的输出。

test.uname;

但是,尝试访问 age 给出的输出为 undefined

问题:

如何使用 test 对象访问 age 属性?

注意:以上是使用Chrome开发者工具-控制台

尝试的

谢谢。

您的 unameage 属性由构造函数直接在它们初始化的每个实例上创建。在这里使用原型继承是没有意义的。只是 运行 两个构造函数:

function sample2() {
    this.age = 21;
}
function sample1() {
    sample2.call(this); // runs the other constructor on this instance
    this.uname = "Andrew";
}

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

I am working with prototypes in 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);

这是在 ES5 中构建原型链的正确方法。

从你的基地开始 class:

// base class definition
function Sample1(name) {
    this.uname = name;
}

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

然后子 class 它,使用适当的原型链接:

// 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;
}

然后您可以使用新继承的 "classes"

// 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);