js 中方法与参数作用域thatthis

JavaScript010

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))

}

谁调用函数,this就指向谁

1.this指向的,永远是对象

2.this指向谁, 不取决与this写在哪,而是取决于函数在哪调用

3.this指向的对象,我们成为函数的上下文context,也叫函数的调用者

1.通过函数名()直接调用:指向window

2.通过对象.函数名()调用:指向这个对象

3.通过数组下标.函数名()调用,指向这个数组

4.通过window内置函数( setInterval setTimeout 等)的回调里调用。指向window

5.函数作为构造函数,new关键字实例化之后调用,指向实例化对象