Ev *_*aus 2 javascript scope prototype reference function
任何人都可以向我解释为什么"b"返回undefined以及如何解决这个问题?当我通过引用调用原型函数时,为什么"this"范围会丢失?
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd').myfunc;
// Returns "asd" correctly
console.log(a)
// Returns undefined??
console.log(b())
Run Code Online (Sandbox Code Playgroud)
===编辑/解决方案===
正如plalx所写,在我的情况下,正确的解决方案是使用.bind().所以结果如下:
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd'),
bfunc = b.myfunc.bind(b)
// Returns "asd" correctly
console.log(a)
// Also returns "asd" correctly!
console.log(bfunc())
Run Code Online (Sandbox Code Playgroud)
如果您想要这种行为,则需要明确地绑定此值.
var c = new MyClass('asd'),
b = c.myfunc.bind(c);
console.log(b());
Run Code Online (Sandbox Code Playgroud)
默认情况下,this将指向leftSide.ofTheDot();调用,或简单地指向调用函数的对象.
注意:呼叫b();与以下内容相同window.b();.
将每个函数绑定到对象实例是可能的,但效率很低,因为函数不再在实例之间共享.
例如
function MyClass(someVal) {
var me = this;
me.someVal = someVal;
me.someFn = function () {
return me.someVal;
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1492 次 |
| 最近记录: |