为什么原型函数的执行上下文(“this”)在本例中是错误的
Why the execution context ("this") of prototypical function is wrong in this example?
原型函数bar
在Node.js环境中的其他地方执行(bind
应该可用)。我希望bar()
函数中的this
是我的对象的实例:
var Foo = function (arg) {
this.arg = arg;
Foo.prototype.bar.bind(this);
};
Foo.prototype.bar = function () {
console.log(this); // Not my object!
console.log(this.arg); // ... thus this is undefined
}
var foo = new Foo();
module.execute('action', foo.bar); // foo.bar is the callback
为什么bar()
日志undefined
和this
不是我的实例?为什么bind
调用没有更改执行上下文?
Function.bind
返回一个值-新绑定的函数-但您只是丢弃该值。Function.bind
不会更改this
(即其调用上下文),也不会更改其参数(this
)。
有其他方法可以得到同样的结果吗?
在构造函数内部执行此操作实际上是错误的,因为bar
位于Foo.prototype
上,因此将其绑定到Foo
的任何一个实例都会破坏所有其他Foo.bar
调用的this
!将其绑定到的意思的位置:
module.execute('action', foo.bar.bind(foo));
或者——也许更简单——根本不在原型上定义bar
:
var Foo = function (arg) {
this.arg = arg;
function bar () {
console.log(this);
console.log(this.arg);
}
this.bar = bar.bind(this);
};
var foo = new Foo();
module.execute('action', foo.bar);
相关文章:
- 错误:this.setValues不是js代码中的函数,请使用googlemapapi
- 为什么会出现错误$this没有定义
- jqueryui:"类型错误:this.menu.element未定义"
- 引导使用谷歌图形错误:this.q.Ee不是中的函数
- 未捕获的类型错误:this.reset不是函数-在ajax调用后清空输入时出错
- 错误:this.getToken 不是一个函数
- 未捕获的类型错误:this.getKeyCode 不是一个函数
- 未捕获类型错误:this.context.router.push不是函数
- Javascript未定义错误:“this”为null
- 类型错误:this.io是未定义的套接字.io.js:639
- JQuery手风琴类型错误:this.slideshow未定义
- 未捕获类型错误:this.source不是函数coffeescript错误
- 未捕获类型错误:this.props.data.map不是函数(使用超级代理)
- Javascript变量作用域问题-错误:类型错误:this.graphics未定义
- 未捕获的类型错误:this.transitionTo不是函数
- 未捕获的类型错误:this.$.AjaxPost.go不是一个以函数为核心的ajax
- 呼叫'FaceNormalsHelper'导致'类型错误:this.update不是函数'
- Javascript类型错误:this.init不是一个函数
- 主干错误'this.模型未定义',请解释'this.model'
- 未捕获的类型错误:$this.文本不是函数