gpt4 book ai didi

javascript - JavaScript 基础的简单 "this"问题

转载 作者:行者123 更新时间:2023-11-30 10:55:04 25 4
gpt4 key购买 nike

var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}

//person.welcome();
// output is
// Hi John
// I was expecting output to be
// Hi Mary

person.welcome.call();
// output is
// Hi Mike
// In this case since no argument is passed to call so this is window and
// I get that window.name is Mike

最佳答案

var name = 'Mike';
var person = {
name: 'John',
welcome: function(){
var name = 'Mary';
return 'Hi ' + this.name;
}
}

this.name 引用对象属性“name”

name 指的是变量“name”

您将通过 return 'Hi ' + name; 获得预期的结果

关于javascript - JavaScript 基础的简单 "this"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2368690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com