this bind apply call

this 是当前函数运行时所属的对象
bind 是指定一个函数运行时的上下文,也就是说把这个函数的this指向绑定到相应对象上,默认的暴露在全局御中的函数this指向widow对象, 严格模式下全局的this为undefined
call和apply的作用是一样的 ,大致是执行某个函数但是用另一个对象的实例替换为上下文执行,call传参数的方法是通过" ,"号的方式分隔着传进去,
apply是直接传一个参数数组进去


call方法:
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。


// 示例1:
var tmp = {
     dd:20, add:
function (a,b){ console.log('tmp.add');console.log(this); return a+b; }, sub:function (a,b) { return a-b; } }; var tmp2 = {
     dd:30, add:
function (a,b) { console.log('tmp2.add');console.log(this); return a+b+5; } }; var res = tmp.add.call(tmp2,3,2); console.log(res); // 5 this.dd:30

//即这里调用tmp.add方法,但是用tmp2对象来替换tmp的add方法执行时的this指向
//示例2:
function dog() {
    this.name = '小黑';
    this.showName = function (){
        console.log(this.name);  
        return this.name;
    }
}

function cat() {
    this.name = '小白';
}

var aDog = new dog();


var res = aDog.showName.call(new cat() );
console.log(res);  // 小白, 小白

通过这样,可以实现js的继承,可以通过prototype(原型来实现继承),也可以直接通过call方法来实现继承

function Animal(name){      
    this.name = name;      
    this.showName = function(){      
        alert(this.name);      
    }      
}          
function Cat(name){    
    Animal.call(this, name);    
}      
    
var cat = new Cat("Black Cat");     
cat.showName(); 
在Cat对象内调用了call方法,从而使this内扩展了Animal从而可以调用animal的方法

也可以多次call 实现多重继承,但多次继承时,实例的this指向最后一行call的类

function Animal(name){      
    this.name = 'animal';      
    this.showName = function(){      
        console.log(this.name);  
        console.log(name);
    }      
  console.log(arguments); // }
function Mao(name) { this.name = 'mao'; } function Cat(name){ this.name = 'cat' Animal.call(this, name); Mao.call(this); } var cat = new Cat("Black Cat"); // 输出 arguments对象: ['Black Cat'] cat.showName(); // 输出 mao , Black Cat

apply方法和call方法作用一样,但由于apply方法会自动把一个数组作为一个一个的参数传入进去,所以,apply可以有一些更巧妙的用法

apply的特性应用如:

1. Math.max 可以实现得到数组中最大的一项

因为Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组

但是它支持Math.max(param1,param2,param3…),所以可以根据刚才apply的那个特点来解决 var max=Math.max.apply(null,array),这样轻易的可以得到一个数组中最大的一项

2.Array.prototype.push 可以实现两个数组合并,同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来装换一下这个数组,即

vararr1=new Array("1","2","3");  

vararr2=new Array("4","5","6");  

Array.prototype.push.apply(arr1,arr2); 

 

原文地址:https://www.cnblogs.com/isdom/p/webclips039.html