JavaScript中this关键字含义及其最佳实践(二)


由于this关键字比较灵活, 因此在书写/阅读相关代码时尤其需要注意.

可读性

简单的解决方案是, 将this的指向对象赋值给一个命名良好的局部变量, 可以提高代码 的可读性.

that

在纯函数, 对象方法, 类构造函数/类实例方法的情形下

例如:

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和代码维护
  • 利于代码压缩

参考

  1. JavaScript Reserved Words
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值