答案 0 :(得分:2)
构造函数没有在原型链中以层次结构图形化,它们构造的对象是图的焦点。
[[proto]]
(可通过obj.__proto__
访问,其中obj
是Object
)和Prototype
之间的区别存在重要区别(和混淆)物体的属性,即。 obj.prototype
。
这段代码可以解释:
function A(name){
this.name = name
this.getName = function(){ return name }
}
function B(name){
A.call(this, name)
}
var b = new B('yep')
var anotherB = new B('me too')
console.log(b.getName()) // yep
/* both B & A constructors inherit from Function but B doesn't inherit from A */
console.log(B instanceof Function && A instanceof Function) //true
console.log(B.prototype === A.prototype) //false
console.log(B.__proto__ === A.__proto__) //true
console.log(B instanceof A) //false
/* an instance of B is not an instance of A */
console.log(b instanceof B) //true
console.log(b instanceof A) //false
/* an instance of B has the prototype of B but not the same [[proto]] as B */
console.log(B.prototype.isPrototypeOf(b)) //true
console.log(b.__proto__ === B.__proto__ ) //false
/* instances of B have the same [[proto]] but not the same [[proto]] as B */
console.log(b.__proto__ === anotherB.__proto__ ) //true

function B
不会从function A
继承。 function A
和function B
都继承自Function
的{{1}}。它们都具有相同的原型链(缩写)。
Object
:function A
- > function A
- > Function
Object
:function B
- > function B
- > Function
这与他们构建的对象不同。在从Object
返回的对象的情况下,原型链是function B
- > B
- > A
。