[英]Why do you need 'this' before a method in a constructor function?
In the code below, I think the way the prototypal chain works (basically) is that if a child object (mike, in this case) doesn't have a method itself, it looks up the prototype chain, via __ proto__, to see if a parent object has it within its prototype object, and if it does, then 'mike' should have access to it.在下面的代码中,我认为原型链的工作方式(基本上)是,如果子对象(在本例中为 mike)本身没有方法,它会通过 __ proto__ 查找原型链以查看如果父对象在其原型对象中拥有它,并且如果有,那么 'mike' 应该可以访问它。 Right?
对?
If that's right, just about, why is 'farewell' is not available to mike?如果这是对的,那么为什么迈克无法使用“告别”? Obviously I can see it's the 'this.'
显然我可以看到它是“这个”。 (or lack thereof) that's making the difference, but if __ proto__ allows a child object to access the methods in the prototype objects of parents, why do we need to bother with this.
(或缺少它)这是有区别的,但是如果 __ proto__ 允许子对象访问父对象的原型对象中的方法,为什么我们需要为此烦恼。 at all??
根本??
Thanks very much!非常感谢!
function PersonConstructor() {
this.greet = function sayHello() {
console.log("hello");
};
farewell = function sayBye() {
console.log("Bye");
};
}
function personFromConstructor(name, age) {
const person = new PersonConstructor();
person.name = name;
person.age = age;
return person;
}
const mike = personFromConstructor("Mike", 30);
console.log(mike.greet); // [Function: sayHello]
console.log(mike.farewell); // undefined
This doesn't have much to do with prototypes at all.这与原型没有太大关系。 What happens when you do
new PersonConstructor()
is, simplified:当你执行
new PersonConstructor()
时会发生什么,简化了:
let obj = {};
/* [ here be dragons and details about setting up prototype chains ] */
PersonConstructor.call(obj); // `this` inside PersonConstructor is obj
return obj;
Essentially, it's equivalent to:本质上,它相当于:
let obj = {};
obj.greet = function sayHello() {
console.log("hello");
};
farewell = function sayBye() {
console.log("Bye");
};
And that should illustrate why farewell
is not ending up as part of the object in any way.这应该说明为什么
farewell
不会以任何方式作为对象的一部分结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.