我在 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 中,继承是基于原型(prototype)的。这意味着没有类(class)。相反,一个对象继承自另一个对象。
你在这里所做的是,对象 B 继承自对象 A,因为:
B.prototype = new A();
那么,现在,userObj
(对象 B 的实例)当然变成了对象 A 的实例,(这就是继承的意义,对吧?)
原来是这样
console.log(userObj instanceof B); // true
console.log(userObj instanceof A); // Also true?
关于javascript - OOP 继承和对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168259/