首页 > 代码库 > JS-this指向

JS-this指向

简记:

  this在不同情况下的指向:

    1.普通函数调用,this指向window对象

var name = "window";    function func() {        var name = "object";         console.log(this.name);    }func(); // window

    2.作为对象的方法被调用,由对象调用,this指向该对象

    var name = "window";    var object = {        name: "object",        func: function() {            console.log(this.name);        }    }    object.func(); // object

    3.使用new构造函数,创建新实例,实例的方法或属性的this指向新实例

    var name = "window";    function Person() {        this.name = "person";    }    Person.prototype.sayName = function() {        console.log(this.name);    }    var person = new Person();    person.sayName();  // person  

    4.apply/call调用的时候,this指向由参数设定的对象值

var o1 = {        name: "o1",        sayName: function() {            console.log(this.name);        }    }    var o2 = {        name: "o2"    }o1.sayName.call(o2); // o2o1.sayName.apply(o2); // o2

 

JS-this指向