javascript - 为什么 bind() 不适用于对象内部另一个函数内的函数?

标签 javascript function this

我对 .bind() 函数有疑问。 我有这段代码,它输出 Window 对象,我不明白为什么。你能向我解释一下为什么bind(this)对函数没有影响吗?

let vakho = {
    name: "salome",
    a: function () {

        let something = function () {
            return this;
        }
        something.bind(this) 

        return {
            f: function () {
                return something();
            }
        }
    },
}

console.log(vakho.a().f())

最佳答案

.bind 返回一个带有附加上下文的新函数。您需要再次将结果分配给something

let vakho = {
    name: "salome",
    a: function () {

        let something = function () {
            return this;
        };
        
        something = something.bind(this); // Assign to the something

        return {
            f: function () {
                return something();
            }
        }
    },
}

console.log(vakho.a().f());
console.log(vakho.a().f().name);

关于javascript - 为什么 bind() 不适用于对象内部另一个函数内的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672780/

相关文章:

javascript - JQuery 悬停不起作用

PHP 更改为 mysqli。 mysqli_connection 不是全局的吗?

coffeescript - 粗箭头 'this' 范围

c++函数调用函数不起作用

c - 在c : do internal states improve speed?中

javascript - 如何直接调用回调修复React类组件中的 'this'?

javascript - 在类创建的对象上返回未定义

javascript - 将 localStorage 包装在 Angular2 服务中?

php - jQuery Galleria 缩略图不显示

javascript - 扁平化 JSON 数据