this、ES3执行上下文

全局的this===window

一般函数中返回的this===window,严格模式下this===undefined

 

作为对象方法的函数的this指对象本身

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

原型链中的 this

相同的概念在定义在原型链中的方法也是一致的。如果该方法存在于一个对象的原型链上,那么this指向的是调用这个方法的对象,表现得好像是这个方法就存在于这个对象上一样。

var o = {
  f : function(){ 
    return this.a + this.b; 
  }
};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

get/set方法同理

 

构造函数中的 this

当一个函数被作为一个构造函数来使用(使用new关键字),它的this与即将被创建的新对象绑定。

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38

 

call、apply、bind

会将第一个参数作为this使用

function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

add.call(o, 5, 7); //16  可变参数列表
add.apply(o, [10, 20]); //34 arguments

 

eventhandler中的this指它所在的DOM对象

<button onclick="alert(this.tagName);">
  Show this
</button>

试一试

 

ES3执行上下文

http://www.imooc.com/video/6491

VO(Variable Object)按照如下顺序填充

函数参数(若未传入,则值为undefined)

函数声明(若发生命名冲突,会覆盖)

变量名称(初始化变量值为undefined,若发生命名冲突,会忽略)

alert(x);//'function'

var x=10;
alert(x);//10
x=20;

function x(){}
alert(x);//20

if(true){
    var a=1;
}else{
    var b=2;
}

alert(a);//1
alert(b);//'undefined'

 

posted on 2015-11-06 23:34  cbwleft  阅读(116)  评论(0)    收藏  举报