js之call()和apply()方法:
call()方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
解释:以其他对象替代thisObj,如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
如果没有提供thisObj参数,那么Global对象将用作thisObj
1、
<script type="text/javascript"> function Animal(name,go){ this.go = go; this.name = name; this.showName=function(){ alert(this.name); } } function Dog(id){ this.id=id; Animal.call(this,"tom123",function(){ alert("gogogo"); }); } var d1 = new Dog(123); d1.showName(); d1.go(); </script>
Dog中Animal.call(this,"tom123",function(){alert("tomcat")});中的this对象被Animal中的this对象替代 var dog = new Dog(123); dog.showName();dog.go();输出结果是tom123,gogogo
2、
function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1);
sub对象呗add对象替代,直接结果4
3、
function Animal(){ this.name = "Animal"; this.showName = function(){ alert(this.name); } } function Dog(){ this.name = "dog0101"; } var animal = new Animal(); var dog = new Dog(); animal.showName.call(dog,","); //animal.showName.apply(dog,[]);
通过call或者apply方法,将元贝属于Animal对象的showName()方法交给对象dog了。so,输出结果dog0101
apply():
语法:apply([thisObj[,argArray]])
解释与call()相似,区别在于,thisObj对象之后的参数需要为argArray->被[]包括
如果没有提供thisObj或者argArray中的任何一个参数,那么Global对象将用作thisObj,且不能传递参数
转载于:https://blog.51cto.com/3264687/1587649