为什么在构造函数中的方法之前需要'this'?

问题描述 投票:-4回答:1

[在下面的代码中,我认为原型链(基本上)的工作方式是,如果子对象(在这种情况下为Mike)本身没有方法,它将通过__proto__查找原型链,看看父对象是否在其原型对象中有它,如果有,那么“麦克”应该可以访问它。对吧?

如果是正确的话,那么迈克为什么无法使用“告别”?显然,我可以看到它是“这个”。 (或缺少)差异,但是如果__ proto__允许子对象访问父对象的原型对象中的方法,为什么我们需要为此而烦恼。完全吗?

非常感谢!

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
javascript oop this prototype proto
1个回答
0
投票

这与原型没有多大关系。简化new PersonConstructor()时会发生什么:

let obj = {};
/* [ here be dragons and details about setting up prototype chains ] */
PersonConstructor.call(obj);  // `this` inside PersonConstructor is obj
return obj;

从本质上讲,它等效于:

let obj = {};
obj.greet = function sayHello() {
  console.log("hello");
};
farewell = function sayBye() {
  console.log("Bye");
};

这应该说明为什么farewell不会以任何方式最终成为对象的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.