难以理解为什么我的 'this' 实施不起作用?

Struggling to understand why my 'this' implementation is not working?

我正在练习this并且我写了一些代码。

我的目标是让 this.MemberName 成为 Tracey 并理解为什么我目前的尝试没有奏效。

当我在变量 assessment 前放置对象名称和点符号时,出现错误。

function family(emotion) {
    return function person() { 
        console.log(
            `The core emotion that ${ this.MemberName } display's is ${ emotion }`
        );
    };
}

var tracey = {
    MemberName: "Tracey",
    age: 0,
    DOB: "29 September 2021",
};

var assessment = family("happy");
tracey.assessment();

我想你是想设置 tracey 对象的 assessment 属性。

您的错误与您对 this 的使用无关,而是因为您在尝试调用它之前没有设置 assessment 属性。

您的代码应如下所示:

function family(emotion) {
    return function person() { 
        console.log(
            `The core emotion that ${ this.MemberName } display's is ${ emotion }`
        );
    };
}

var tracey = {
    MemberName: "Tracey",
    age: 0,
    DOB: "29 September 2021",
};

tracey.assessment = family("happy");
tracey.assessment();

lejlun的回答是正确的

如果可以接受,您可以将 属性 直接分配给对象

var tracey = {
  MemberName: "Tracey",
  age: 0,
  DOB: "29 September 2021",
  assessment: function(emotion){
    console.log(
      `The core emotion that ${ this.MemberName } displays is ${ emotion }`
    );
  }
}
tracey.assessment('happy')

如果您想在 tracey 上调用 assessment() 而不将其分配为 属性,您可以传递方法 person() 应该使用的范围作为 'this' 使用 Function.prototype.apply 如下所示:

function family(emotion) {
  return function person() { 
    console.log(
      `The core emotion that ${ this.MemberName } displays is ${ emotion }`
    );
  };
}

var tracey = {
  MemberName: "Tracey",
  age: 0,
  DOB: "29 September 2021",
};

function assessment(somePerson, emotion) {
  // family returns person()
  // we pass somePerson as 'this' to person()
  family(emotion).apply(somePerson);
}

assessment(tracey, 'happy');

为什么您的代码不起作用:

function family(emotion) {/*...*/}
var tracey = {/*...*/};

// assessment is assigned to the global scope, 
// the same scope where family and tracey reside
var assessment = family("happy");

// we try to call a property of tracey called assessment
tracey.assessment();

// Uncaught TypeError: tracey.assessment is not a function

console.log(tracey.assessment);

// undefined