-
Notifications
You must be signed in to change notification settings - Fork 52
再探this指向
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();
})()
- 普通函数调用,this为全局对象或是undefined
- 作为对象的方法,this为那个对象
- new 表达式,this为以该函数为原型的新创建的对象
- 使用 apply/call指定 this
- 用bind绑定固定的this
- 事件处理函数中的this是当前的触发事件的DOM元素(event.currentTarget)
- this跟代码中的位置没关系,是在执行的时候赋值的
- this是不会沿着变量作用域、原型链或闭包结构向上查找
-
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了