关于call与apply的一些认识

Posted on 2017-01-12 23:48  码上快乐  阅读(156)  评论(0)    收藏  举报

关于call与apply,他们主要是改变函数体this的指向,apply()有两个参数,第一参数是this,第二个参数是arguments或者数组,call(this,xxx),两者前面必须为函数,如下:

//函数中有prototype与call,appy两个方法
function adds(num1,num2){
			return num1+num2;
		};
	function sum1(a,b){
			return adds.apply(this,arguments);//apply()是以数组的方式传递的
		};
		function sum2(a,b){
			//return adds.apply(this,[a,b])
			return adds.apply(window,[a,b])
		};
	function sum3(a,b){
			return adds.call(this,a,b);//call是以列举的方法传递
		}

		var t = sum1(100,2);
		var t2 = sum2(1,5);
		var t3 = sum3(2,6);
		console.log(t);//102
		console.log(t2);//6
		console.log(t3);//8

  以下中的text()中的this指向的是str

        var str = {
			dec:"从你的身旁走过"
		};
		function text(){
			console.log(this.dec);
		};
		text.call(str);            

  如以下一段代码:

        var str = {
            infos:function(a,b){
                return "你的名字"+a+",今年"+b+"岁了";
            }
        };
        function info(a,b){
            var t = this.infos(a,b);
            console.log(t);
        };
        info.call(str,"哈哈",20);//你的名字哈哈,今年20岁了
        info.apply(str,['嘻嘻',18]);//你的名字嘻嘻,今年18岁了

对比以上call与apply的唯一区别是,apply第二参数是数组,call()的第二个参数传递的需要参数,在没有任何参数的条件下,没有什么区别

var str = {
            price:function(name,price){
                //this.name = "orange";
                //this.price = 20;
                this.name = name;
                this.price = price;
                return this.name+"==="+this.price;
            }
        };
function info2(c,d){
            var r = this.price(c,d);
            console.log(r);//orange=====20
        }
        //info2.call(str);
info2.apply(str,['orange',20]);

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3