美文网首页
JavaScript中的this

JavaScript中的this

作者: 王儒林 | 来源:发表于2016-07-04 14:15 被阅读0次

JavaScript中的this

Tags: JavaScript 开发


[toc]

最近在学习ReactNative,免不了被坑在JS上,跟Java和Objective-C不同,JS方法里的this显得很另类,有点令人困惑。

什么是this

要说清this是什么,可以从Function.prototype.call()方法说起,这个方法近似于function调用的原始实现,它的方法签名是这样的:

fun.call(thisArg[, arg1[, arg2[, ...]]])

其中thisArg代表的就是方法里的this,而其他参数,则是arg1arg2以可变长度参数的形式传递。调用的过程和结果如下:

function hello(thing) {  
  console.log(this + " says hello " + thing);
}
hello.call("Yehuda", "world") //=> Yehuda says hello world  

JavaScript里的其他方法调用方式大致可以看做这个调用的语法糖[1]

在ES5前,function里的this默认会是window或者global对象,而使用了严格模式的ES5,全局function里的this将会是undefined

// this:
hello("world")
// desugars to:
hello.call(undefined, "world");  

对于一个方法来说this并不是一成不变,具体是什么取决于调用这个方法的时机:

function hello(thing) {  
  console.log(this + " says hello " + thing);
}

person = { name: "Brendan Eich" }  
person.hello = hello;

person.hello("world") // still desugars to person.hello.call(person, "world")

hello("world") // "[object DOMWindow]world" //具体环境决定

通常我们把this形容为上下文就是因为这个。

那么问题来了

JavaScript中,我们经常要将方法传递给其他方法,当做回调函数,比如最近学习的ReactNative,JSX中经常要将方法作为参数传递:

render() {
    return (
        <ListView dataSource={this.props.dataSource} renderRow={this._renderRow}
/>
    )
}
...

_renderRow(itemData) {
    return (
        <TouchableHighlight onPress={this._rowPressed} >
            ...not important
        </TouchableHighlight>
    )
}

_rowPressed() {
    ...not important
}
 

细心的盆友看出来了,我这样写是不行的,ListView的renderRow方法是由react执行的,它调用_renderRow的时候,上下文this必然不是声明render方法所在的实例,_renderRow方法里的this._rowPressed必然是undefined

JavaScript中Function是一等类型,可以被显式传递,所以必然会出现上下文不对的问题,在没有深入研究过的开发者手中,往往忽视这个问题,写出大坑。

如何使this确定

bind

这个问题也困扰了JS开发者很久,如何解决呢?
在ES5之前,人们通过一个简单方法帮助改正错误的this:

var person = {  
  name: "Brendan Eich",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}
var boundHello = function(thing) { return person.hello.call(person, thing); }
boundHello("world"); 

尽管我们可以在任何地方调用boundHello方法,可是boundHello实际上是对上下文和原始hello方法进行了封装,所以最终hello里的this始终是person

这个方法最终被ES5引入的Function.prototype.bind方法所替代,所以现在我们的代码里可以这样使用:

var boundHello = person.hello.bind(person);  
boundHello("world") // "Brendan Eich says hello world"  

所以,前文里面困扰了我的ReactNative问题,解决方法也许是:

render() {
    return (
        <ListView dataSource={this.props.dataSource} renderRow={this._renderRow.bind(this)}
/>
    )
}
...

_renderRow(itemData) {
    return (
        <TouchableHighlight onPress={this._rowPressed.bind(this)} >
            ...not important
        </TouchableHighlight>
    )
}

_rowPressed() {
    ...not important
}

而考虑到ReactNative,render方法的性能要求,不能在render过程中创建新方法,所以最终解决方案是这样的:

constructor() {
    super()
    this._renderRow = this._renderRow.bind(this)
    this._rowPressed = this._rowPressed.bind(this)
}
render() {
    return (
        <ListView dataSource={this.props.dataSource} renderRow={this._renderRow}
/>
    )
}
...

_renderRow(itemData) {
    return (
        <TouchableHighlight onPress={this._rowPressed} >
            ...not important
        </TouchableHighlight>
    )
}

_rowPressed() {
    ...not important
}

另外bind(this)在ES6里还有新语法糖:

this._renderRow = ::this._renderRow
this._rowPressed = ::this._rowPressed

不过在Babel的实现中说明了这个语法是highly experimental的,所以最后用不用,follow your heart~

Fat Arrow

ES6引入了箭头匿名方法,它的方法体里的this是会绑定给初始化它的实例的,所以constructor里的方法也可以改为:

this._renderRow = (rowData) => this._renderRow(rowData)
this._rowPressed = () => this._rowPressed()

这种方法的缺点是参数个数是固化的,如果想处理原方法的更多参数,需要在这里显式写出这些参数,不太灵活,毕竟我们只想绑定this,不关心参数。

鸣谢

bind新语法
what's 'this'
jsx中不推荐使用bind和箭头函数
mozilla bind文档

谢谢收看


  1. 严格来说不是,只是近似,方便下文讲解。

相关文章

  • 1body中添加js

    1 中的 JavaScript JavaScript 函数和事件上面例子中的 JavaScript 语句,会...

  • JS中的类型转换

    JavaScript 中的类型转换 JavaScript 基本数据类型 JavaScript 中的一共有 8 中内...

  • js中的this

    javascript中的this javascript中的this与java中的this有点不同。ECMAScri...

  • JavaScript中的字符串

    @(javascript)[js字符串][toc] JavaScript中的字符串 字符串是JavaScript中...

  • 06-JavaScript数组和函数

    JavaScript数组 JavaScript中的数组可以存储不同类型的数据 JavaScript中的数组是引用类...

  • Client's JavaScript

    什么是JavaScript? JavaScript的运行环境? 浏览器中JavaScript可以做什么? 浏览器中...

  • javascript中的this

    一般说到JS的this,都会想起在函数中变来变去的this。但是事情的发生都是有规则的约束,JS中的this也不例...

  • JavaScript中的this

    什么是this? 首先对this的下个定义:this是在执行上下文创建时确定的一个在执行过程中不可更改的变量。th...

  • JavaScript中的this

    JavaScript中的this很容易让人迷惑,但弄清楚后其实还是很好区分的。JavaScript中的this总是...

  • javascript中的this

    在javascript中的this大致可以理解成谁调用的this就指向谁 全局环境中的this 函数中的this ...

网友评论

      本文标题:JavaScript中的this

      本文链接:https://www.haomeiwen.com/subject/xvgcjttx.html