有人能给我解释一下为什么绑定方法在这些例子中不起作用吗?

Can someone explain to me why the binding method doesn't work in these examples

本文关键字:方法 不起作用 绑定 为什么 解释 一下      更新时间:2023-09-26

在本例中,当我将bind方法添加到调用更深的函数的末尾时。绑定方法不起作用

    var body = document.body;
function Depth() {
    this.state = "I am inside here";
    this.deep = function() {
        function deeper() {
            body.innerHTML = this.state;
        }.bind(this);
        deeper();
    }
}

var obj = new Depth();
obj.deep();

在这个例子中,当我将bind方法添加到调用deep方法的新对象的末尾时。绑定方法不起作用

    var body = document.body;
function Depth() {
    this.state = "I am inside here";
    this.deep = function() {
        function deeper() {
            body.innerHTML = this.state;
        }
        deeper();
    }
}

var obj = new Depth();
obj.deep().bind(this);

我已经知道该怎么做才能使函数正常运行并打印出这个。国家代码。但是,我想解释一下为什么前两个例子不起作用,因为这是我编写代码的第一个想法。下面是最后一个正常工作的例子

var body = document.body;
function Depth() {
    this.state = "I am inside here";
    this.deep = function() {
        var state = this.state
        function deeper() {
            body.innerHTML = state;
        }
        deeper();
    }
}

var obj = new Depth();
obj.deep();

'Function.prototype.bind()'返回一个新方法而不改变原来的方法,所以你必须将新方法赋值给一个变量,然后你可以使用它:

    var deeper = function deeper() {
        body.innerHTML = this.state;
    }.bind(this);

    obj.deep = obj.deep.bind(this); // you can bind an object method, and then reassign it to the original property