有人能给我解释一下为什么绑定方法在这些例子中不起作用吗?
Can someone explain to me why the binding method doesn't work in these examples
在本例中,当我将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
相关文章:
- Meteor-添加用户自定义字段的方法不起作用
- 在 JQUERY 中创建 HTML 后,Jquery 方法不起作用
- 为什么这个扩展方法不起作用
- Splice()方法不起作用
- Angularjs-向工厂传递数据的方法不起作用
- Knockout和bread.js的take方法不起作用Paging
- javascript注入$http-post方法不起作用
- 为什么pulk()和where()方法不起作用
- Ajax get 方法不起作用
- 当我将javascript代码放在外部站点.js文件中时,Ajax页面方法不起作用
- getJSON 方法不起作用
- Jquery ajax get 方法不起作用
- jQuery AddClass 方法不起作用
- ScriptManager.RegisterStartupScript() 方法不起作用 - ASP.NET,C#
- 为什么JavaScript方法不起作用
- 为什么 findRandom() mongoose for node.js 方法不起作用
- BackboneJS的设置方法不起作用
- 从javascript调用 asp.net 页面方法不起作用
- 主干.js对以前的方法不起作用进行建模
- toExponential() 方法不起作用