js this

时间:2019-09-30
本文章向大家介绍js this,主要包括js this使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
由于 Javascript(简称:JS)中的 this 理解起来较为复杂,使得很多入门新手和一些进入前端圈子有些年限的工程师们都对其的用法有些模糊。所以今天为大家带来 Javascript(简称:JS) 中 this 的用法详解。

this 永远指向 调用 包含 自己(this本身) 的 函数 对应的对象。
也就是说,包含 this 的函数 只在乎是谁调用了它,跟在哪里进行的函数声明没有关系。

下面就来举个例子说明:

function test(){
    var a = 1;
    console.log(this.a);
}

test(); //undefined
如果函数在最外层直接运行,默认绑定的对象是 window,因为 test() 是被window对象调用的,所以这里的 this.a 对应的应该是 全局变量(或者叫window变量) 而不是test函数里的局部变量,由于 在 window 对象中没有声明 变量a,所以输出 undefined。

下面我们对代码进行改造一下:

var a = 2; //window对象下的变量

function test(){
    var a = 1;
    console.log(this.a);
}

test(); // 打印结果为 2
下面再来分析一个经典的例子:

var name = 'China';
var obj = {
    name : 'America',
    show : function() {
        console.log(this.name)
    }
}

obj.show(); // America
从上述代码可以看出,包含 this 的函数是 show(),而show()函数通过对象obj调用的,所以 this.name 指向 obj 中的 name(America);

我们再来对代码进行改造:

var name = 'China';
var obj = {
    name : 'America',
    show : function() {
        return function(){
            console.log(this.name);
        }
    }
}

var a = obj.show();
a(); // China
这里的 obj.show() 返回的是一个匿名函数

function(){
    console.log(this.name);
}
然后赋值给 变量a,等价于:

var a = function(){
    console.log(this.name);
}

或

function a(){
    console.log(this.name);
}
所以 最后执行的 a()== window.a(), 函数a 里面的 this.name 指向 window.name('China'),所以最终输出 China。

看到这里,相信大家对 this 已经有个比较清楚的认识了,下面给大家介绍4种 this 常用的场景。
1. 在一般函数方法中使用 this 指代全局对象

function test(){
  this.x = 1;
  alert(this.x);
}
test(); // 1
2. 作为对象方法调用,this 指代上级对象

function test(){
  alert(this.x);
}

var obj = {};

obj.x = 1;
obj.m = test;
obj.m(); // 1
3. 作为构造函数调用,this 指向 new 出的对象

function test(){
    this.name = 'China';
}

var t = new test();
console.log(t.name); //'China'
4. apply, call 调用
function Animal(){
    this.name = 'animal';
}

function Cat(){
    Animal.call(this);
}

var cat = new Cat();
console.log(cat.name);// 'animal'
以上便是 this 全部的解答。

原文地址:https://www.cnblogs.com/xiaowie/p/11613086.html