提问人:himanshu thakur 提问时间:3/3/2022 更新时间:3/3/2022 访问量:25
这在javascript中是什么意思?为什么我的第二个输出未定义?[复制]
What does this means in javascript ? Why is my second output undefined? [duplicate]
问:
谁能解释为什么我的输出未定义。我试图弄清楚这里有什么问题,对不起,我是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 {}
答:
0赞
brk
3/3/2022
#1
内部函数不知道是什么意思,所以它指定了全局的this。你可以用innerFunc
this
bind
this
innerFunc
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();
评论
this
innerFunc();
this
window
window.age
x.sayName();
x.
this
x
this