发布于 4年前

JavaScript this使用的上下文

JavaScript里this的值主要是由调用的上下文决定。

全局上下文

在全局的上下文里调用this,它的值为全局对象Global,浏览器为window:

<script type="text/javascript">
    document.write(this);  //[object Window]
</script>

直接的函数调用

直接的函数调用,this的值为全局对象Global,浏览器环境为window。

全局的上下文直接调用:

function func()
{
   return this;
}
document.write(func());  //[object Window]

在对象里直接的函数调用:

var context = "global";

var obj = {  
    context: "object",
    method: function () {                  
        function f() {
            var context = "function";
            return this + ":" +this.context; 
        };
        return f(); //函数直接调用
    }
};
document.write(obj.method()); //[object Window]:global 

赋值对象方法给变量,直接调用变量函数

var obj = {
  method: function() {
    return this;
  }
}

var func = obj.method;
document.write(func());  //[object Window]

这种情况很容易对this判断为obj对象,但实际值为全局对象,浏览器为window。

作为对象的方法调用

做为对象的方法调用,this的值为所调用的对象。

基本的方法调用

var obj = {
    name: "obj",
    f: function () {
        return this + ":" + this.name;
    }
};
document.write(obj.f());  //[object Object]:obj

把纯函数添加给对象的方法

var obj = {
    name: "obj",
}

function func() {
    return this + ":" + this.name;
}

obj.func = func; //func函数添加给obj的func方法
document.write(obj.func()); //[object Object]:obj

对象嵌套调用方法

var obj = {
    name: "obj",
    nestedobj: {
        name:"nestedobj",
        f: function () {
            return this + ":" + this.name;
        }
    }            
}
document.write(obj.nestedobj.f()); //[object Object]:nestedobj

这些情况下,this的值都为调用的对象。

构造函数调用

在构造函数里使用this,this的值为使用构造函数构造的对象。


function Func()
{
    this.name = "function name";
}

var obj = new Func(); //构造obj对象
document.write(obj.name); //function name,函数里的this即为obj

call(), apply()和bind()给this绑定指定的对象

在JavaScript有一些函数可以让调用者给this绑定指定的对象,这些函数包括:

  • Function.prototype.apply( thisArg, argArray )
  • Function.prototype.call( thisArg [ , arg1 [ , arg2, ... ] ] )
  • Function.prototype.bind( thisArg [ , arg1 [ , arg2, ... ] ] )
  • Array.prototype.every( callbackfn [ , thisArg ] )
  • Array.prototype.some( callbackfn [ , thisArg ] )
  • Array.prototype.forEach( callbackfn [ , thisArg ] )
  • Array.prototype.map( callbackfn [ , thisArg ] )
  • Array.prototype.filter( callbackfn [ , thisArg ] )

调用这些函数时,thisArg就是this所绑定的对象。

把o对象绑定到this

function add(inc1, inc2)
{
    return this.a + inc1 + inc2;
}

var o = { a : 4 };
document.write(add.call(o, 5, 6)+"<br />"); //15
document.write(add.apply(o, [5, 6]) + "<br />"); //15
var g = add.bind(o, 5, 6);      
document.write(g()+"<br />");    //15

var h = add.bind(o, 5); 
document.write(h(6) + "<br />"); //15
©2020 edoou.com   京ICP备16001874号-3