The call apply bind js

<! - If the first argument call and apply written is null, then this points to a Window object ->
call()
a.call (b, reference 1, reference 2) // A replacement b
a. Method .call (b, []) // A method b has not there
a.call (the this) // the this b-b in a function call all inherit
var b = new b (parameter);. b method (argument) // called with arguments
Description: call method can be used in place of another object calls a method. The method may call a function of the object context specified by the new object from the initial thisObj context change. If no thisObj parameters, then the Global object is used as thisO BJ.
There are a = {
user: "dream child"
fn:function(){ //方法 function fn(){}
console.log(this.user);
}
}
var b = a. fn ;
b.call (A); / / out, put back
In addition to the first method of call parameters may also add a number of parameters, as follows:
There are a = {
user: "dream child"
fn:function(e,ee){
console.log(this.user);
}
}
var b = a.fn;
b.call (a, 1,2); // sub Dream
 
  1. apply() 语法:apply([thisObj[,argArray]]) 定义:应用某一对象的一个方法,用另一个对象替换当前对象。 说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数
apply方法和call方法有些相似,它也可以改变this的指向
var a = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
var b = a.fn;
b.apply(a);
 
同样apply也可以有多个参数,但是不同的是,第二个参数必须是一个数组,如下:
 
var a = {
user:"追梦子",
fn:function(e,ee){
console.log(this.user); //追梦子
console.log(e+ee); //11
}
}
var b = a.fn;
b.apply(a,[10,1]); // b.call(a,10,1)
 
或者
var a = {
user:"追梦子",
fn:function(e,ee){
console.log(this.user); //追梦子
console.log(e+ee); //520
}
}
var b = a.fn;
var arr = [500,20]; //数组
b.apply(a,arr);
 
//注意如果call和apply的第一个参数写的是null,那么this指向的是window对象
var a = {
user:"追梦子",
fn:function(){
console.log(this); //Window ……
}
}
var b = a.fn;
b.apply(null);
 
3 bind 绑定
bind方法和call、apply方法有些不同,但是不管怎么说它们都可以用来改变this的指向。
var a = {
user:"追梦子",
fn:function(){
console.log(this.user);
}
}
var b = a.fn;
b.bind(a);
 
我们发现代码没有被打印,这就是bind和call、apply方法的不同,实际上bind方法返回的是一个修改过后的函数。
var a = {
user:"追梦子",
fn:function(){
console.log(this.user);
}
}
var b = a.fn;
var c = b.bind(a);
console.log(c); // function() { [native code] }
那么我们现在执行一下函数c看看,能不能打印出对象a里面的user
var a = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
var b = a.fn;
var c = b.bind(a);
c(); //a.fn();
ok,同样bind也可以有多个参数,并且参数可以执行的时候再次添加,但是要注意的是,参数是按照形参的顺序进行的。
var a = {
user:"追梦子",
fn:function(e,d,f){
console.log(this.user); //追梦子
console.log(e,d,f); //10 1 2
}
}
var b = a.fn;
var c = b.bind(a,10);
c(1,2);
call和apply都是改变上下文中的this并立即执行这个函数,bind方法可以让对应的函数想什么时候调就什么时候调用,并且可以将参数在执行的时候添加,这是它们的区别,根据自己的实际情况来选择使用。

Guess you like

Origin www.cnblogs.com/bjyx/p/11993246.html