这在javascript中意味着什么?为什么我的第二个输出未定义



//有人能解释为什么我的输出未定义吗。我正试图弄清楚这里的问题是什么。很抱歉,我是javascript的新手。

function Person() {
this.name = 'Jack',
this.age = 25,
this.sayName = function () {

//enter code here this is accessible
console.log(this.age);

function innerFunc() {

// this refers to the global object
console.log(this.age);
console.log(this);
}

innerFunc();
}
}

let x = new Person();
x.sayName();

Output:
25
undefined
Window {}
内部函数innerFunc不知道this是什么意思,所以它指定了全局this。您可以使用innerFuncbindthis

function Person() {
this.name = 'Jack';
this.age = 25;
this.sayName = function() {
console.log(this.age);
function innerFunc() {
console.log(this.age);
console.log(this);
}
innerFunc.bind(this)();
}
}
let x = new Person();
x.sayName();

最新更新