js 中方法与参数作用域thatthis

JavaScript09

js 中方法与参数作用域thatthis,第1张

this是JS的关键字。代表函数运行时,自动生成的一个内部对象,this代表的是当前对象,只能在函数内部使用.

var that=this就是将当前的this对象复制一份到that变量中

还有---箭头函数---可以解决 that/this 作用域的问题。

没有参数

一个参数 (括号可加,可不加)

多个参数

在JavaScript中,我们经常用到函数绑定,而当你需要在另一个函数中保持this上下文时,使用Function.prototype.bind()会很方便.

var myObj = {

specialFunction: function () {

},

anotherSpecialFunction: function () {

},

getAsyncData: function (cb) {

cb()

},

render: function () {

var that = this

this.getAsyncData(function () {

that.specialFunction()

that.anotherSpecialFunction()

})

}

}

myObj.render()

为了保持myObj上下文,设置了一个变量that=this,这样是可行的,但是没有使用Function.prototype.bind()看着更整洁:

render: function () {

this.getAsyncData(function () {

this.specialFunction()

this.anotherSpecialFunction()

}.bind(this))

}