由于this
关键字比较灵活, 因此在书写/阅读相关代码时尤其需要注意.
可读性
简单的解决方案是, 将this
的指向对象赋值给一个命名良好的局部变量, 可以提高代码 的可读性.
that
在纯函数, 对象方法, 类构造函数/类实例方法的情形下
- 推荐将
this
赋值局部变量that
. - 不推荐使用
self
作为局部变量名, 见JavaScript Reserved Words.
例如:
var test = function (value) {
var that = this;
that.hello = value;
console.log(that.hello)
// do something
// ...
};
var uncleWang = {
_name: 'WangXiaobo',
getName: function () {
var that = this;
return that._name;
},
displayName: function () {
var that = this,
name = that.getName();
console.log('The name is ' + name);
}
};
function Person (name) {
var that = this;
that._name = name;
}
Person.prototype.getName = function () {
var that = this;
return that._name;
};
Person.prototype.displayName = function () {
var that = this,
name = that.getName();
console.log('name: ' + name);
};
事件监听器
在事件监听器中, 推荐将this
赋值给不叫that
且命名有意义的变量. 比如:
// $ 为jQuery
$('h1, h2', document.body).on('click', function () {
var el = this;
// do something
});
或者
// $ 为jQuery
$('h1, h2', document.body).on('click', function () {
var $el = $(this);
// do something
});
这样做可增强代码的可读性, 当代码比较复杂时尤其明显.
/**
* @param {HTMLElement} container
* @param {HTMLElement} hook
*/
function DialogBad(container, hook) {
this._container = container;
this._hook = hook;
this.bindEvent();
}
DialogBad.proptotype.bindEvent = function () {
$('li', this._container).on('click', function () {
$(this).toggle();
});
$(this._hook).on('click', function () {
$(this._container).show();
}.bind(this));
};
/**
* @param {HTMLElement} container
* @param {HTMLElement} hook
*/
function DialogGood(container, hook) {
var that = this;
that._container = container;
that._hook = hook;
that.bindEvent();
}
DialogGood.proptotype.bindEvent = function () {
var that = this;
$('li', that._container).on('click', function () {
var li = this;
$(li).toggle();
});
$(that._hook).on('click', function () {
$(that._container).show();
});
};
代码压缩
JavaScript代码压缩工具, 如Closure Compiler, YUI Compressor, UglifyJS, 一般能压 缩局部变量, 但不能压缩this
关键字. 如果将this
赋值给局部变量, 那么this
能够 间接被压缩.
总结
将this
赋值局部变量的好处:
- 增强代码的可读性, 易于debug和代码维护
- 利于代码压缩