[英].prototype and [[prototype]]. Why is .prototype an empty object?
I am actually very confused with prototypes right now despite reading most articles on StackOverflow.尽管阅读了有关 StackOverflow 的大多数文章,但我现在实际上对原型非常困惑。
function Foo() {
}
Foo.prototype.speak = function() {
console.log('Foo');
};
function Bar() {
}
console.log(Bar.prototype); // {}
Bar.prototype = Object.create(Foo.prototype);
console.log(Bar.prototype); // {} ----- (1)
Bar.prototype.speak = function() { // ----------(2)
console.log('Bar');
};
console.log(Bar.prototype); // { speak: [Function] } ----- (3)
Question:题:
1) Why is (1) an empty object after Object.create
. 1)为什么(1)在Object.create
之后是一个空对象。 Shouldn't it turn an object with a speak method
from Foo
?难道它不应该使用Foo
的speak method
转换一个对象吗?
2) What am I actually changing on (2) ?? 2)我实际上在(2)上改变了什么?? The Bar
object or the prototype
object ? Bar
对象还是prototype
对象? What is actually happening?实际发生了什么?
3) What's happening on (3) . 3) (3)上发生了什么。
4) How is [[prototype]] involved in all of this? 4) [[prototype]] 如何参与所有这些? What I do know is [[prototype]] is used for look ups if the current object does not contain a property.我所知道的是,如果当前对象不包含属性,则 [[prototype]] 用于查找。
Just to be sure, .prototype !== [[prototype]]
but [[prototype]] === __proto__
?可以肯定的是, .prototype !== [[prototype]]
但是[[prototype]] === __proto__
?
Sorry if this is a duplicate.对不起,如果这是重复的。 Because I can't seem to answer those questions despite multiple similar questions.因为尽管有多个类似的问题,但我似乎无法回答这些问题。
You can't change the prototype of a function/object by simply trying to assign it.您不能通过简单地尝试分配来更改函数/对象的原型。 You need to set it at the time of object creation or you should use ES6 features to change it.您需要在创建对象时设置它,或者您应该使用 ES6 特性来更改它。
So, Bar.prototype = Object.create(Foo.prototype);
所以, Bar.prototype = Object.create(Foo.prototype);
doesn't make any sense.没有任何意义。
[[prototype]]
is the internal representation of the real prototype of an object. [[prototype]]
是对象真实原型的内部表示。
Probably you should re-arrange your test case based on these fundamentals and seek explanation.也许您应该根据这些基本原理重新安排您的测试用例并寻求解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.