JS中的this指向

来源:互联网 发布:软件项目任务书 编辑:程序博客网 时间:2024/05/24 06:20

1、 普通函数: this指向 window

    function foo() {        function fn() {            console.log(this);        }        console.log(this); // window  只用函数的调用方法来判断this的指向    }    foo();

2、构造函数: this指向实例化对象

    function Parent(name) {        this.name = name;        console.log(this);    }    var p1 = new Parent('zhangsan');    var p2 = new Parent('lisi');

3、方法调用 :this指向函数的调用者

    function fun(val) {        console.log(val);        console.log(this);        console.log(this.age);        console.log(this === obj);    }    var obj = {age: '18'};    obj.say = fun;    fun();    obj.say();

4、call和apply方法

    var name = 'global';    var obj = {        name: 'obj',        dose: function () {            this.name = 'dose';//当前的this指向obj(将obj.name的值改成dose)            return function () {                return this.name;//当前的this指向window            }        }    };    console.log(obj.dose()());//global    console.log(obj.dose().call(obj));//dose
原创粉丝点击