javascript 中 this 的用法

this,javascript 中的一个关键字。

它是在运行时,在函数体内自动生成的一个对象,因此只能在函数体内使用 

 下面让我们直截了当的来看下 this 的几种使用方式


1. 函数调用

函数的通常用法,这种属于全局调用,因此这时 this 就代表者全局对象

var x = 1;

function fn(){
    console.log(x); // 变量 x,这时是全局的变量 x
}
fn(); //1

2. 匿名函数的使用

匿名函数执行时,this 代表者全局

var x = 1;
var fn = function(){
    console.log(this.x);
}
fn(); // 1

//常用闭包式匿名函数

(function(){
    console.log(this.x)
})() //1

3. 作为对象调用

当函数作为对象调用的时候,此时的 this 是这个上级对象

function fn(){
    console.log(this.x); //this 指向 obj
}
var obj = {
    x:1,
    m:fn
}    

obj.m(); // 1 

 4. 构造函数使用

当通过构造函数,生成一个新对象时,此时,this 是指这个新对象

function Fn(){
    this.x = 1; 
}

var x = 2; 

var obj = new Fn();

obj.x // 1

5. apply / call 时调用

apply call 是函数的一个方法,主要就是用来改成函数调用的,第一个参数就是要改变的对象,因此,this 就是指这第一个参数,如果第一个参数无,那 this 就代表者全局

var x = 1;
function fn(){
    console.log(this.x);
}
var obj = {
    x: 2,
    m:fn
}

obj.m.apply(); // 1

注意!有关 apply 、call 的详细内容将在下一篇讲解

猜你喜欢

转载自blog.csdn.net/qq_30523685/article/details/81449830
今日推荐