内部函数
//有人能解释为什么我的输出未定义吗。我正试图弄清楚这里的问题是什么。很抱歉,我是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。您可以使用innerFunc
bind
this
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();