obj1.method1.call(obj2,arg1,arg2)
call的作用就是把obj1的方法放到obj2上使用,后面的arg1..这些做为参数传入
例:
- function add(a,b)
- {
- alert(a+b);
- }
- function sub(a,b)
- {
- alert(a-b);
- }
- add.call(sub,3,1);
这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4);
// 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。
例:
- function Animal(){
- this.name = "Animal";
- this.showName = function(){
- alert(this.name);
- }
- }
- function Cat(){
- this.name = "Cat";
- }
- var animal = new Animal();
- var cat = new Cat();
- //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
- animal.showName.call(cat); //输入结果为"Cat"
- //animal.showName.apply(cat,[]);
- function Animal(name){
- this.name = name;
- this.showName = function(){
- alert(this.name);
- }
- }
- function Cat(name){
- Animal.call(this, name);
- }
- var cat = new Cat("Black Cat");
- cat.showName();
cat类继承Animal类, Animal.call(this, name); 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法,Cat对象就能够直接调用Animal的方法以及属性了.
例:多重继承
- function Class10()
- {
- this.showSub = function(a,b)
- {
- return(a-b);
- }
- }
- function Class11()
- {
- this.showAdd = function(a,b)
- {
- return(a+b);
- }
- }
- function Class2()
- {
- Class10.call(this);
- Class11.call(this);
- }
- var test=new Class2();
- console.log(test.showSub(29,17));
- console.log(test.showAdd(29,17));
还有 callee,caller..