在这个例子中,当我将bind方法添加到调用deeper.函数的末尾时。绑定(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方法的新对象的末尾时。绑定(bind)方法不起作用。
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);
我已经知道如何使函数正常运行并打印出 this.state 代码。但是,我想要一些解释为什么前两个示例不起作用,因为这些是我必须编写代码的第一个想法。这是正常运行的最后一个示例。
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
关于javascript - 有人可以向我解释为什么绑定(bind)方法在这些示例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947501/