前几天我查看了一些开源代码,发现他们使用var _ = this;
来维护对原始代码的引用。现在作为Javascript的新手,我想知道这是不是很糟糕的做法?
我已经看过并使用过self = this
,that = this
,me = this
,但使用下划线可以让代码在我眼中更容易阅读。特别是因为在插件中,我的写作需要经常使用。我的眼睛可以更容易地专注于实际变量/功能。
现在我的问题是你对使用_ = this;
这是我所指的代码。
https://github.com/kenwheeler/slick/blob/master/slick/slick.js
答案 0 :(得分:1)
这里的问题是你真的需要这样做。
假设你有一个对象叫另一个回调。
现在使用变量_你可以有这样的东西:
function Person( name ) {
var _ = this;
_.name = name;
_.dog = new Dog( "fido" );
_.dog.goEat( function() {
// do something when dog finished to eat
_.goOutWithYourDog( );
} );
...
在这种情况下,您可以在不使用_。
的情况下执行相同的操作function Person( name ) {
this.name = name;
this.dog = new Dog( "fido" );
this.dog.goEat( function() {
// do something when dog finished to eat
this.goOutWithYourDog( );
}.bind(this) );
...
使用bind可以包装你的函数并在其中使用它作为Person对象。
您也可以使用close与bind,因此您让回调函数具有由调用者绑定的上下文,但您可以使用Person对象。 当你必须使用回调事件时,这个os很有用。更好用_因为只有在需要时才使用它。
function Person( name ) {
this.name = name;
(function(person){
$( ... ).on( "click", function( e ) {
var value = this.value;
person.doSomeStuffWithTheValue( value );
} );
})( this );