javascript回顾之this

一、this

this肯定指向的是一个对象!!!一般在函数里使用this

1.在全局作用下,调用this,this指向global也就是windows。函数声明,匿名函数,函数表达式在全局中调用this指向window

2.new关键词构造的对象,this指向创建该对象的对象

eg:

var fn1 = function(){
    this.x = 10;
    this.y = 20;
}

var fn2 = new fn1();

fn2是从fn1中new出的一个实例,也是对象fn1。this指的是fn1对象而不是fn1函数

3.this当前的函数为对象属性的时候,this指向该对象

eg:

    var obj = {
        x:10,
        Y:10,
        fn1:functon(){
            this.x = 20;
        }
    }
obj.fn1();

this指向该对象obj

下面是一些关于this的面试题:

    var length = 10;
    function fn() {
          console.log(this.length);
    }

    var obj = {
          length: 5,
         method: function(fn) {
              fn();
               arguments[0]();
          }
};

obj.method(fn, 1);

解析:第一次输出为10,第二次为2,第二次执行相当于arguments调用方法,this指向arguments,这里传了两个参数,所以arguments的长度为2.

var foo = {

       bar: function () {

        return this.baz;

        },

       baz: 1

};

(function () {

       return typeof arguments[0]();

})(foo.bar);

A. “undefined”

B. “object”

C. “number”

D. “function”

答案:A

解析:arguments【foo.bar】(),this指向arguments,return arguments.baz,arguments里只有foo.

var foo = {

    bar: function () {

        return this.baz;

    },

    baz: 1

};

typeof (f = foo.bar)();

A. “undefined”

B. “object”

C. “number”

D. “function”

答案:A

解析:(f = foo.bar)() = fn()这是函数,this就指向函数,windows里找不到baz,只有foo里有baz.

Share