1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width">
6 <title>JS中的call()和apply()方法</title>
7 </head>
8 <body>
9 JS中的call()和apply()方法
10 <pre>
11 call 方法定义:
12
13 语法:call(this Obj[,arg1[,arg2[,[argN]]]])
14 定义:调用一个对象的一个方法,以另一个对象替换当前对象。
15 说明:
16 call方法可以用来代替另一个对象调用一个方法。call方法可以将一个函数的对象上下文从初始的上下文改变为由 this Obj 指定的新对象。
17 如果没有提供 this Obj 参数,那么Global 对象被用作this Obj。
18
19 apply方法:
20
21 语法:apply([this Obj[,argArray]])
22 定义:应用某一对象的一个方法,用另一个对象替换当前对象。
23 说明:
24 如果argArray 不是一个有效的数组或者不是arguments 对象,那么将导致一个 TypeError。
25 如果没有提供argArray 和 thisObj 任何一个参数,那么Global 对象将被用作 thisObj,并且无法被传递任何参数。
26
27
28 apply 第二个参数必须是数组或类数组 arguments
29 </pre>
30
31
32 </body>
33 </html>
1 // var add = function (a,b){
2 // return (a+b);
3 // }
4
5 // var sub = function (a,b){
6 // return (a-b);
7 // }
8 // console.log(sub.call(add,2,3))
9
10 /*
11 function AAA(){
12 // this.name='john';
13 this.say=function(){
14 console.log('Hello, I\'m '+ this.name);
15 }
16 }
17 AAA.prototype.name='john';
18
19 function ABB(){
20 // this.name='samith';
21 }
22 ABB.prototype.name='samth';
23 var aa1 = new AAA();
24 var ab1 = new ABB();
25
26
27 aa1.say.call(ab1,","); //this 指向 ABB对象
28 aa1.say()
29
30
31 aa1.say.apply(ab1,[]);
32
33 */
34
35
36 /*
37 function Animal( name,say ){
38 this.name = name;
39 this.say = say;
40 this.lang = function(){
41 console.log("The animal " + this.name + " " + this.say )
42 }
43
44 }
45
46 function Cat( name,say ){
47 //继承Animal 的属性和方法
48 Animal.call( this, name, say);
49 }
50
51 var cata = new Cat( 'black-cat','meow');
52 cata.lang();
53
54
55 function Dog( name,say,work ){
56 this.work =work;
57 Animal.call(this,name,say);
58 }
59
60 Dog.prototype.fav = function(){
61 console.log(this.work);
62 };
63
64 var dog_td = new Dog( 'Teddy','bark','狩猎');
65 dog_td.lang();
66 dog_td.fav();
67
68 */
69
70
71 function C1(){
72 this.fnadd = function(a,b){
73 return (a+b);
74 }
75 }
76
77 function C2(){
78 this.fnsub = function(a,b){
79 return (a-b);
80 }
81 }
82
83 function C3(){
84 C1.call(this);
85 C2.call(this);
86 }
87
88 var c_3 = new C3();
89 console.log(c_3.fnadd(2,5));