JS—-this指向(一)

栏目: JavaScript · 发布时间: 7年前

内容简介:平时用this有些混乱,所以写个总结。没有箭头函数之前,我们说this就是函数运行时所在的环境对象,但是在箭头函数中this就是定义时所在的对象,先说大家熟知的:函数运行时所在的环境对象。1、作为函数调用,this指向全局对象

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

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

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

var q = 'window'
var func = functio {
    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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git (Second Edition)

Pro Git (Second Edition)

Scott Chacon、Ben Straub / Apress / 2014-11-9 / USD 59.99

Scott Chacon is a cofounder and the CIO of GitHub and is also the maintainer of the Git homepage ( git-scm.com ) . Scott has presented at dozens of conferences around the world on Git, GitHub and the ......一起来看看 《Pro Git (Second Edition)》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具