gpt4 book ai didi

javascript - JS 构造函数中 "this"的值返回 "undefined"

转载 作者:行者123 更新时间:2023-12-02 16:44:55 27 4
gpt4 key购买 nike

所以我有一个构造函数

    var APP = function(name){

this.appName = name

}

还有一个原型(prototype)函数

    APP.prototype.test = function(){

console.log(this.appName)

}

然后我创建一个新的 APP() 并尝试测试功能。

    var app = new APP("ieps")
var testing = app.test

console.log(app.test()) // returns "ieps"
console.log(testing()) // returns undefined

为什么 test() 返回未定义? test() 应该做与 app.test() 相同的事情,因为我只是引用 app.test。

最佳答案

您必须将对象绑定(bind)到函数

var app = new APP("ieps");
var testing = app.test.bind(app);

console.log(testing());

http://jsbin.com/kiyiyutili/2/edit

编辑:来自MDN docs for .bind :

"The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called."

关于javascript - JS 构造函数中 "this"的值返回 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177507/

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