js中可以改变作用域的三种方式(改变this)

第一种方式:使用apply()方法: 



function sum(x, y) {

 alert(this); return x + y;//这里的this指的是callS对象方法

}

function callS() {

callS.callSum1(1, 2);

}

callS.callSum1 = function (x, y) {

 alert(this);//这里的this是callS方法

var s = sum.apply(this, arguments);

return s;

}

 callS();



第二种放方法:使用call()方法: 



有关call方法:



window.color="red";

var o ={color:"blue"};

function sayColor(a,b){alert(this.color);}

sayColor();//red

sayColor.call(this,1,2);//red

sayColor.call(window,1,2);//red

sayColor.call(o,1,2);//blue  



l在使用call()方法时,必须明确地传入每一个参数。结果和apply一样。

其实apply和call真正的强大用途在于,能够扩充函数赖以运作的作用域:



这样扩充的最大好处,就是对象不需要与方法有任何耦合关系。

 第三种方法:使用new关键字:



function Person(name,age){

  this.name=name;

  this.age=age;  this.sayName=function(){alert(this.name);};

}

var p1 = new Person("james",27);

var p2 = new Person("coook",24);

p1.sayName(); p2.sayName();

lnew关键字:

0开辟堆空间 1创建对象;2将构造函数作用域赋值给新对象(this就指向了该新对象);3执行构造函数中的代码(为新对象添加属性);4返回新对象

 

 

你可能感兴趣的:(this)