Skip to content
LYF edited this page Apr 5, 2016 · 15 revisions

第一个例子

  var property = "window property";
  function test(){
    this.property = "test object property";
  }
  test.property = "test function property";
  var fn = test.fn = test.property.fn = function(){
      alert(this.property);
  }
  fn(); // window property
  test.fn(); // test function property
  var t = new test();
  alert(t.property); // test object property

第二个例子

 var property = "window property";

 var obj = {
   property:"obj property",
   sayProperty:function(){
     alert(this.property);
   }
 }

 obj.sayProperty(); // obj property

 var fn = obj.sayProperty;

 fn();  // window property

 (obj.sayProperty)(); // obj property

第三个例子

// 如果不适用严格模式,那么两个函数内部的this都是指向window的
"use strict";

(function(){
    console.log("IIFE inner",this); // undefined
    function test(){ 
        console.log("this inner",this) // undefined
    }
    test();
})()

结论

  1. 普通函数调用,this为全局对象或是undefined
  2. 作为对象的方法,this为那个对象
  3. new 表达式,this为以该函数为原型的新创建的对象
  4. 使用 apply/call指定 this
  5. 用bind绑定固定的this
  6. 事件处理函数中的this是当前的触发事件的DOM元素(event.currentTarget)
  7. this跟代码中的位置没关系,是在执行的时候赋值的
  8. this是不会沿着变量作用域、原型链或闭包结构向上查找
  9. this只存在于函数调用期间,在变量作用域中不存在跟第7条是一个意思,这里列出来,是为了在不同的语境下理解

一个面试题

var length = 10;
    function fn(){
        alert(this.length);
    }
    var obj = {
        length:5,
        method:function( fn /* , a */ ){
            fn(); // 10
            arguments[0](); //1
            // this.method.arguments[0]();
            // console.dir(arguments);
            // console.dir(this.method.length);
            // console.dir(arguments.length);
        }
    }
    obj.method(fn);

第一个弹出10应该好理解,第二个弹出1 arguments并不是一个数组 arguments[0]这个0就相当于arguments的一个属性,跟obj[attrName]是一样的 arguments0就跟调用obj[attrName]一样,这时候fn里面的this就指向arguments了 这样就能理解后一个为什么是1了

https://segmentfault.com/q/1010000004867221?_ea=712571

Clone this wiki locally