Ezi*_*io_ 2 javascript oop this self
我们假设我们有以下代码:
var MyClass = (function(){
var _this;
function MyClass(inputVal){
_this = this;
this.value = inputVal;
}
MyClass.prototype.getValue = function(){
return this.value;
}
MyClass.prototype.getValue2 = function(){
return _this.value;
}
return MyClass;
})();
Run Code Online (Sandbox Code Playgroud)
让我们做两个类的实例:
var instance1 = new MyClass(10);
var instance2 = new MyClass(20);
Run Code Online (Sandbox Code Playgroud)
现在,如果我们使用console.log()我们看到的值:
instance1.getValue(); // 10
instance1.getValue2(); // 20
Run Code Online (Sandbox Code Playgroud)
var MyClass = (function(){
var _this;
function MyClass(inputVal){
_this = this;
this.value = inputVal;
}
MyClass.prototype.getValue = function(){
return this.value;
}
MyClass.prototype.getValue2 = function(){
return _this.value;
}
return MyClass;
})();
var instance1 = new MyClass(10);
var instance2 = new MyClass(20);
console.log(instance1.getValue());
console.log(instance1.getValue2());Run Code Online (Sandbox Code Playgroud)
为什么会这样?很明显,_this变量获取最新创建的实例属性.如何解决?我需要保留一份副本this.谢谢!
编辑:
这是真实的情况
var HoverEffects = (function(){
var _this;
function HoverEffects($nav){
_this = this;
this._$activeNav = $nav.siblings('.active_nav');
this._$hoverableLis = $nav.find('>li');
this._$activeLi = $nav.find('>li.active');
if(!$nav.length || !this._$hoverableLis.length || !this._$activeNav.length || !this._$activeLi.length) return;
if(this._$activeNav.hasClass('bottom')){
this._$activeNav.align = 'bottom';
this._$activeLi.cssDefault = {
left: this._$activeLi.position().left,
width: this._$activeLi.width()
};
}
else if(this._$activeNav.hasClass('left')){
this._$activeNav.align = 'left';
this._$activeLi.cssDefault = {
top: this._$activeLi.position().top,
height: this._$activeLi.height()
};
}
else{
return;
}
this._$hoverableLis.hover(
function(){
// How to set the correct this inside this function?
if(this._$activeNav.align === 'bottom'){
this._$activeNav.css({
left: $(this).position().left,
width: $(this).width()
});
}
else if(this._$activeNav.align === 'left'){
this._$activeNav.css({
top: $(this).position().top,
height: $(this).height()
});
}
},
function(){
// Same here, wrong this
this._$activeNav.css(this._$activeLi.cssDefault);
}
);
}
return HoverEffects;
})();
var sideNavHoverMagic = new HoverEffects($('#side-navigation'));
var primaryNavHoverMagic = new HoverEffects($('#primary-navigation'));
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
每次打电话new MyClass,_this = this都会跑.第二次覆盖第一次.
所以_this指的是new MyClass(20),这意味着当你getValue2从任何 MyClass实例调用时,20将返回,因为所有 MyClass实例都引用相同的_this值.
根据对该问题的评论:
如果您尝试传递绑定到适当上下文的函数,则有多种方法可以确保this引用正确的对象.在继续之前,请阅读"'this'关键字如何运作?" 因为我没有理由在这里重复所有这些.
如果您绑定事件回调,例如在构造函数中:
function Example(something) {
something.addEventListener(..event.., this.callback, false);
}
Example.prototype.callback = function () {
this.doStuff();
this.doMoreStuff();
};
Run Code Online (Sandbox Code Playgroud)
回调将具有错误的this值,因为它没有被调用this.callback,它只被调用为:
fn = this.callback;
fn(); //no reference to this
Run Code Online (Sandbox Code Playgroud)
你可以通过多种方式解决这个问题.
Function.prototype.bind您可以绑定callback各自实例上的每个实例.这非常简洁:
function Example(something) {
//generate a new callback function for each instance that will
//always use its respective instance
this.callback = this.callback.bind(this);
something.addEventListener(..event.., this.callback, false);
}
Example.prototype.callback = function () {
this.doStuff();
this.doMoreStuff();
};
Run Code Online (Sandbox Code Playgroud)
that = this您可以创建回调(关闭)内的构造和引用构造函数中的变量.
function Example(something) {
//every Example object has its own internal "that" object
var that = this;
this.callback = function () {
//this function closes over "that"
//every instance will have its own function rather than
//a shared prototype function.
that.doStuff();
that.doMoreStuff();
}
something.addEventListener(..event.., this.callback, false);
}
Run Code Online (Sandbox Code Playgroud)
() => {}(Fat Arrow语法)如果您使用的是ES2015,则可以使用"胖箭头"语法创建不创建新上下文的lambda:
function Example(something) {
this.callback = () => {
//the callback function doesn't create a new "this" context
//so it referes to the "this" value from "Example"
//every instance will have its own function rather than
//a shared prototype function.
that.doStuff();
that.doMoreStuff();
}
something.addEventListener(..event.., this.callback, false);
}
Run Code Online (Sandbox Code Playgroud)