OOP 继承和对象实例

OOP inheritance and objects instaces

我正在研究 JavaScript 中的继承和 OOPS。我创建了 'A' 对象和 'B' 对象,并将 'B' 的所有属性继承到 'A'。

当我使用 'instanceof' 检查新创建的对象实例时,我发现两个对象都是真实的。
但是我只使用 'B' 构造函数创建了对象。

function A(){
    this.a = "test1",
    this.b = "test2"
}

function B(){
    this.c = "test3",
    this.d = "test4"
}

B.prototype = new A();

var userObj = new B();

console.log(userObj instanceof B); // true
console.log(userObj instanceof A); // true, How this can be true?

在JavaScript中,继承是基于原型的。这意味着没有 类。相反,一个对象继承自另一个对象。

你在这里所做的是,对象 B 继承自对象 A,因为:

B.prototype = new A();

所以,现在,userObj(对象 B 的实例)当然变成了对象 A 的实例,(这就是继承的意义,对吧?)

原来如此

console.log(userObj instanceof B); // true
console.log(userObj instanceof A); //  Also true?

console.log(userObj instanceof A);你一定会得到true。这是按照 JavaScript 标准。

当您创建 B 的对象继承 A 的所有属性时,该对象包含指向 [=15= 的 link __proto__ ].

因此 instanceof 将在对象 B 的原型链中找到 A's 构造函数。

这就是 returns 正确的原因。

原型对象有一个名为 constructor.First 的内置 属性 从 chorme 控制台看到这张图片,我将讨论

在您的代码中 B.prototype = new A(); => 此语句将 B 的原型设置为 A.So B 的原型对象的实例,并将其构造函数 属性 分配给 A();

console.log(userObj.constructor // it will show A.But it is not true

记住它不是 userObj 的 constructor.The 你得到的构造函数来自原型 obj。

console.log(userObj instanceof A); // true, How this can be true?

因为 userObj 是 B.And B 继承自 A.So 的实例,所以 userObj 也是 A.But 的实例,您可以使用 属性 操作构造函数设置为 B

B.prototype.constructor=B;