对于函数来说每个函数都一个 call() 和 apply(), 它们的作用就是在特定的作用域中调用函数, 实际上等于设置函数体内的 this 对象的值.
劫持函数中的方法
- function addOne(a,b){
- //this(a,b);
- alert(a+b);
- }
- function minOne(a,b){
- alert(a-b);
- }
- //addOne(33,32);
- addOne.call(minOne,7,10);
劫持面向对象中的方法
- function Goo(){
- this.name="虎",
- this.sayName=function(){
- alert(this.name);
- }
- }
- function Yoo(){
- this.name="蛇";
- }
- var i=new Goo();
- //i.sayName();
- var m=new Yoo();
- i.sayName.call(m);// 输出蛇, 劫持方法, 先构造实例化对象才能调用 sayName 方法.
实现继承
- function Fun(name){
- this.name=name;
- this.sayNm=function(){
- alert(this.name);
- }
- }
- function Blue(name){
- this.name=name;
- Fun.call(this,name);// 实现继承让 Blue 对象有 Fun 对象拥有的方法.
- }
- var a=new Fun("热点");
- a.sayNm();
- var b=new Blue("奇迹");
- b.sayNm();
来源: http://www.qdfuns.com/note/49226/d8b406074dee6243188e6ad5fb2b3900.html