代码改变世界

call经常用到的地方

2016-07-05 18:45  孤独大兔子  阅读(187)  评论(0编辑  收藏  举报

看完这几个下例子,会对学习js有所帮助
1、小猫和小狗

function food(){}
food.prototype={
  food:'fish',
  say:function(){
   console.log('i love '+this.food);
 }
}
var blackCat=new food();
blackCat.say();

//blackCat会说,i love fish

//如果又来了一只小狗,小狗喜欢吃骨头,但又不想改变food的方法
var  dog={food:'boon'};
blackCat.say.call(dog);

//那么小狗就会说,i love boon

 2、我想要什么动物就要什么动物

    function Animal() {                     //是什么小动物就叫什么名字
        this.showName = function() {
            console.log(this.name);  
        }
    }

    function Person(name) {
        this.name = null;
        this.Init = function(name) {    
            this.name = name;
        }
        this.Init(name);
    };

    var nameShowing = new Animal();
    var dark = new Person("我是小鸭");     //想生产什么就生产什么
    var chick = new Person("我是小鸡");     //想生产什么就生产什么
    nameShowing.showName.call(dark);   //我是小鸭
    nameShowing.showName.call(chick);   //我是小鸡

比较上面的方法,一锅端的方式,全部继承,本质一样

    function Animal() {                     //是什么小动物就叫什么名字
        this.showName = function() {
            console.log(this.name);  
        }
    }

    function Person(name) {
        this.name = null;
        this.Init = function(name) {    
            this.name = name;
        }
        this.Init(name);
    };

/*  var nameShowing = new Animal();
    var chick = new Person("我是小鸭子");     //想生产什么就生产什么
    nameShowing.showName.call(chick);   //我是小鸭*/

    var chick = new Person("我是小鸭子");  
    Animal.call(chick);  
    chick.showName();       //我是小鸭子

3、用一个空对象来模仿

    function Person(name, age){  
        this.name = null;  
        this.age = null;  
        this.showPersonInfo = function(){  
            document.write("Name: " + this.name + "<br>");  
            document.write("Age: " + this.age + "<br>");  
        };  
        this.Init = function(){  
            this.name = name;  
            this.age = age;  
        };  
        this.Init(); 
        this.aaa=123; 
    }  
      
    var animal = new Object();  
    Person.call(animal, "小鸭子", 18);   //animal具有了animal的属性和方法,不包含原型中的

4、实现继承,之前已经写过了,这里就不写了

5、借用其他对象的方法

//判断是否是一个数组
var s=[1,2,3];
Object.prototype.toString.call(s);  
//"[object Array]"
//利用Math.max来取数组最大值
Math.max.apply(null,[1,2,5])     //5
//借用Array.prototype对象上的方法,往arguments中添加一个新的元素,通常会借用Array.prototye.push方法
(function(){
  Array.prototype.push.call(arguments,3)
  console.log(arguments)
})(1,2)     //[1,2,3]
//利用数组push方法,把任意对象传入值 Array.prototype.push
var a={};
Array.prototype.push.call(a,"frist");
a[0];       //frish   
a.length;   //1
//借用Array.prototype.slice方法,把arguments转成真正的数组
(function(){
  Array.prototype.slice.call(arguments)
  console.log(arguments)
})(1,2)         //[1,2]
//截去arguments列表的头一个元素,可以借用Array.prototype.shift方法
(function(){
  Array.prototype.shift.call(arguments)
  console.log(arguments)
})(1,2)     //[2]

 

@