javascript中的this

/*
* 全局对象
* this = window
* 在全局作用域中它的 this 执行当前的全局对象(浏览器端是 Window,node 中是 global)。
*/
console.log(this);      // Window


/*
* @ 函数中执行, 调用
* @ 一个函数被直接调用的时候, 属于全局调用,this指向全局对象
*/
function test(){
    console.log(this);      // Window 
}
test();

/*
* 严格模式 ‘use strict’;
* @ 如果在严格模式的情况下执行纯粹的函数调用,那么这里的的 this 并不会指向全局,而是 undefined,这样的做法是为了消除 js 中一些不严谨的行为:
*/
(function (){
  "use strict";
 console.log(this);         // undefined
})();


/*
* 作为对象的方法调用
* this指向当前的这个对象
*/
var obj = {
    name: "qiutc",
    foo: function(){
        console.log(this.name);     // "qiutc" this指向当前对象
    }
}
obj.foo();

// 还可以这么做
function test(){
    console.log(this.name);         // "qiutc" this指向当前对象
}
var obj = {
    name: "qiutc",
    foo: test
}
obj.foo();
// 因为在 js 中一切都是对象,函数也是一个对象,对于 test ,它只是一个函数名,函数的引用,它指向这个函数,当 foo = test,foo 同样也指向了这个函数。


/*
* 把对象的方法赋值给一个变量,然后直接调用这个变量
* this会指向window
*/
var obj = {
    name: "qiutc",
    foo: function(){
        console.log(this);
    }
}
var test = obj.foo;
test();         // window
// 当我们把 test = obj.foo ,test 直接指向了一个函数的引用,这时候,其实和 obj 这个对象没有关系了,所以,它是被当作一个普通函数来直接调用,因此,this 指向全局对象。


/*
* setTimeout的this指向全局对象(window)
* 用一个变量 _this 来储存this
*/
var obj = {
    name: 'qiutc',
    foo: function() {
        console.log(this);
    },
    foo2: function() {
        console.log(this);
        var _this = this;
        setTimeout(function() {
            console.log(this);  // Window

            console.log(_this);  // Object {name: "qiutc"}
        }, 1000);
    }
};
// obj.foo2();

/*
* 作为一个构造函数使用
* @ this 指向了这个构造函数调用时候实例化出来的对象
*/
function Person(name){
    this.name = name;
    console.log(this);
}
var p = new Person("Alan");     // Person {name: "Alan"}

// 构造函数其实也是一个函数,如果我们把它当作一个普通函数执行,这个 this 仍然执行全局:
function Person(name) {
    this.name = name;
    console.log(this);
}
var p = Person('qiutc');        // Window


/*
* call函数改变this指向
* 在执行 foo.call(obj) 的时候,函数内的 this 指向了 obj 这个对象
*/
var obj = {
    name: "Alan"
};

function foo(){
    console.log(this);
}
foo.call(obj);          // Object {name: "Alan"}

// 为对象中的方法指定一个 this
var obj = {
    name: "Alan",
    foo: function(){
        console.log(this);
    }
}
var obj2 = {
    name: "fuck you"
}
obj.foo.call(obj2);     // Object {name: "fuck you"}
// 执行函数的时候这里的 this 指向了 obj2

 

posted @ 2016-10-19 19:48  AlanTao  阅读(166)  评论(0编辑  收藏  举报