新会员白菜网送体验金前端开发
新会员白菜网送体验金用户体验

JS—-this指向(一)

平时用this有些混乱,所以写个总结。

没有箭头函数之前,我们说this就是函数运行时所在的环境对象,但是在箭头函数中this就是定义时所在的对象,先说大家熟知的:函数运行时所在的环境对象。

1、作为函数调用,this指向全局对象

var q = 'window'
var func = function {
    console.log(this.q)
}

func()   //window

2、作为对象的方法调用,该对象即为调用上下文,this指向该对象。

var q = 'window'
var func = function() {
    console.log(this.q)
}

var obj = {
    q: 'obj',
    func: func,
    anotherObj: {
        q: 'anotherObj',
        func: func
    }
}

obj.func()   //obj
obj.anotherObj.func() //anotherObj

3、作为构造函数调用,构造函数试图初始化这个新创建的对象,并将这个对象作为其调用上下文,this 指向这个新创建的对象。

var q = 'window'

function Func() {
    this.q = 'Func'
    console.log(this.q)
}

var obj = new Func  //Func

console.log(this.q)  //window

4、通过函数的call/apply方法间接调用, call/apply方法的第一个参数是调用上下文,在函数体内,通过this获得对它的引用。

var q = 'window'

function func() {
 console.log(this.q)
}

var obj = {
 q: 'obj'
}

func.apply()  //window
func.call() //window

func.apply(obj) //obj
func.call(obj) //obj
注册就送10元(78)
未经允许不得转载:大前端 » JS—-this指向(一)
分享到: 更多 (0)

评论 3

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #3

    freight forwarder for amazon – freight forwarder website template – freight forwarder network – freight forwarder queensland – freight forwarder quora

  2. #2

    I’d ought to seek advice from you here. Which isn’t some thing It’s my job to do! I spend time reading a post that could make people believe. Also, thanks for allowing me to comment!

    Adrian Vannaman2周前 (04-08)回复
  3. #1

    When it is important to possess your current mindset guided toward the full-time successful ecommerce business, it truly is helpful, specifically first inside your Online job, in the studying blackberry curve, to test one or two packages with your quit period. Find the feel belonging to the Online marketing industry as well as together study a little about HTML, Scripts, producing interesting photographs and even building your very first web site! This may most end up being realized like a ‘spare time’ sctivity. Do not carrier the management right until you have the particular confidence within your total capacity in order to make normal income.

themebetter 国内更好的WordPress主题服务商

立即前往
博聚网