Scenario One: Define a Class A, give it a GetName method, define a Class B, give it a SetName method, before a only need to get its name,b and only need to set its name, but now there are new requirements, both A and b need to set and get their respective name, Swollen, come on, let call () and apply () take you to fly ~ ~ ~
1 //define a Class A2 functionA (name) {3 This. Name=name;4 }5 //Class A A method to get the name6A.prototype.getname=function(){7 return This. Name;8 }9 //define a Class BTen functionB (name) { One This. Name=name; A } - //Class B A method for setting the name -B.prototype.setname=function(rename) { the This. Name=rename; - } - //Create Object A, b - varA=NewA ("I am a"), b=NewB ("I am B"); + //B wants to know its name. -A.getname.call (b);//Result: "I am B" PS: Point this to B +A.getname.apply (b);//Result: "I am B" PS: Point this to B A //a want to change its name atB.setname.call (A, "I am AA");//PS: Point this to a -B.setname.apply (a,["I am AA"]);//PS: Point this to a -A.getname ()//Result: "I am AA"
JavaScript call () &apply ()