js中的call()方法理解和使用

来源:互联网 发布:淘宝店铺图片 编辑:程序博客网 时间:2024/06/04 20:59

官方对call()使用格式是:obj1.call(obj2,arg0,arg1,arg2...);

官方对它的解释是:调用一个对象的方法,以另外一个对象替换当前对象;对应上面的式子就是,obj1对象替换obj2对象,然后再调用以(arg0, arg1, arg2...)为参数的方法。


官方的标准:

call([thisObj[,arg1[, arg2[, [,.argN]]]]]) 
参数 
thisObj 
可选项。将被用作当前对象的对象。 
arg1, arg2, , argN 
可选项。将被传递方法参数序列。 
说明 
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 

如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

------------------------------------------------------------------------------------------- 

举个网上常用的例子:

function add(a,b){    alert(a+b);}function sub(){    alert(a - b);}add.call(sub, 3, 1);//add替代sub对象,add.call(sub, 3, 1) == add(3,1)就是add(3, 1),结果是alert(4)// 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。 


举一个复杂的地址:
Shape.js

function Shape(){    this._name = "shape";    this.setName1 = function(name){        this._name = name;    }    this.getName1 = function(){        return this._name;    }}
Rect.js

function Rect() {    this.width = 10;    this.height = 10;    function getWidth(){        return this.width;    }    function setWidth(width){        this.width = width;    }    function getHeight(){        return this.height;    }    function setHeight(height){        this.height = height;    }    Shape.call(this);}
app.js

var shape = new Shape();shape._name = "nihao";//alert(shape._name);//结果是"nihao"var rect = new Rect();rect._name = "rect";alert(rect._name);//结果是"rect"//alert(Shape._name);//结果是undefined//alert(rect.getName1());//如果不加括号那么弹出来的就是getName1的代码,而不是结果

实际上就实现了Rect继承了Shape

写的比较好的博客:

http://www.cnblogs.com/sweting/archive/2009/12/21/1629204.html

http://www.cnblogs.com/frostbelt/archive/2012/04/01/2428014.html


0 0
原创粉丝点击