function MyObject(element) {this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);};
MyObject.prototype.onClick = function(e) {var t=this; //do something with [t]...//without bind the context of this function wouldn't be a MyObject//instance as you would normally expect.};
// This data variable is a global variablevar data = [{name:"Samantha", age:12},{name:"Alexis", age:14}]var user = {// local data variabledata :[{name:"T. Woods", age:37},{name:"P. Mickelson", age:43}],showData:function (event) {var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1console.log (this.data[randomNum].name + " " + this.data[randomNum].age);}}
// Assign the showData method of the user object to a variablevar showDataVar = user.showData;showDataVar (); // Samantha 12 (from the global data array, not from the local data array)/*This happens because showDataVar () is executed as a global function and use of this insideshowDataVar () is bound to the global scope, which is the window object in browsers.*/
// Bind the showData method to the user objectvar showDataVar = user.showData.bind (user);// Now the we get the value from the user object because the this keyword is bound to the user objectshowDataVar (); // P. Mickelson 43
bind() allow us to borrow methods
// Here we have a cars object that does not have a method to print its data to the consolevar cars = {data:[{name:"Honda Accord", age:14},{name:"Tesla Model S", age:2}]}
// We can borrow the showData () method from the user object we defined in the last example.// Here we bind the user.showData method to the cars object we just created.cars.showData = user.showData.bind (cars);cars.showData (); // Honda Accord 14
function greet (gender, age, name) {// if a male, use Mr., else use Ms.var salutation = gender === "male" ? "Mr. " : "Ms. ";if (age > 25) {return "Hello, " + salutation + name + ".";}else {return "Hey, " + name + ".";}}
我们可以使用bind()来curry这个greet函数
// So we are passing null because we are not using the "this" keyword in our greet function.var greetAnAdultMale = greet.bind (null, "male", 45);
greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."
var greetAYoungster = greet.bind (null, "", 16);greetAYoungster ("Alex"); // "Hey, Alex."greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."
apply() or call() to set this value
The apply, call, and bind methods are all used to set the this value when invoking a method, and they do it in slightlydifferent ways to allow use direct control and versatility in our JavaScript code.
The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method.
Here is one example to use call or apply to set this in the callback function.
// Define an object with some properties and a method// We will later pass the method as a callback function to another functionvar clientData = {id: 094545,fullName: "Not Set",// setUserName is a method on the clientData objectsetUserName: function (firstName, lastName) {// this refers to the fullName property in this objectthis.fullName = firstName + " " + lastName;}};
function getUserInput (firstName, lastName, callback, callbackObj) {// The use of the Apply method below will set the "this" value to callbackObjcallback.apply (callbackObj, [firstName, lastName]);}
// The clientData object will be used by the Apply method to set the "this" valuegetUserInput ("Barack", "Obama", clientData.setUserName, clientData);// the fullName property on the clientData was correctly setconsole.log (clientData.fullName); // Barack Obama
Borrow functions with apply or call
Borrow Array methods
Let’s create an array-like object and borrow some array methods to operate on the our array-like object.
// An array-like object: note the non-negative integers used as keysvar anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
// Make a quick copy and save the results in a real array:// First parameter sets the "this" valuevar newArray = Array.prototype.slice.call (anArrayLikeObj, 0);console.log (newArray); // ["Martin", 78, 67, Array[3]]
// Search for "Martin" in the array-like objectconsole.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true
另一种常见的情况是将arguments转换为数组,如下所示
// We do not define the function with any parameters, yet we can get all the arguments passed to itfunction doSomething () {var args = Array.prototype.slice.call (arguments);console.log (args);}
doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"]
Borrow other methods
var gameController = {scores :[20, 34, 55, 46, 77],avgScore:null,players :[{name:"Tommy", playerID:987, age:23},{name:"Pau", playerID:87, age:33}]}var appController = {scores :[900, 845, 809, 950],avgScore:null,avg :function () {var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {return prev + cur;});this.avgScore = sumOfScores / this.scores.length;}}// Note that we are using the apply () method, so the 2nd argument has to be an arrayappController.avg.apply (gameController);console.log (gameController.avgScore); // 46.4// appController.avgScore is still null; it was not updated, only gameController.avgScore was updatedconsole.log (appController.avgScore); // null
Use apply() to execute variable-arity function
The Math.max is one example of variable-arity function,
// We can pass any number of arguments to the Math.max () methodconsole.log (Math.max (23, 11, 34, 56)); // 56
但是如果我们有一个数组要传递给Math.max呢?我们不能这样做:
var allNumbers = [23, 11, 34, 56];// We cannot pass an array of numbers to the the Math.max method like thisconsole.log (Math.max (allNumbers)); // NaN
var allNumbers = [23, 11, 34, 56];// Using the apply () method, we can pass the array of numbers:console.log (Math.max.apply (null, allNumbers)); // 56
您有三个汽车your_scooter , your_car and your_jet,它们以相同的机制(方法)开始。我们用方法push_button_engineStart创建了一个对象automobile。
var your_scooter, your_car, your_jet;var automobile = {push_button_engineStart: function (runtime){console.log(this.name + "'s" + ' engine_started, buckle up for the ride for ' + runtime + " minutes");}}
function printBye(message1, message2){console.log(message1 + " " + this.name + " "+ message2);}
var par01 = { name:"John" };var msgArray = ["Bye", "Never come again..."];
printBye.call(par01, "Bye", "Never come again...");//Bye John Never come again...
printBye.call(par01, msgArray);//Bye,Never come again... John undefined
//so call() doesn't work with array and better with comma seperated parameters
//printBye.apply(par01, "Bye", "Never come again...");//Error
printBye.apply(par01, msgArray);//Bye John Never come again...
var func1 = printBye.bind(par01, "Bye", "Never come again...");func1();//Bye John Never come again...
var func2 = printBye.bind(par01, msgArray);func2();//Bye,Never come again... John undefined//so bind() doesn't work with array and better with comma seperated parameters
var car = {registrationNumber: "007",brand: "Mercedes",
displayDetails: function(ownerName){console.log(ownerName + ' this is your car ' + '' + this.registrationNumber + " " + this.brand);}}car.displayDetails('Nishant'); // **Nishant this is your car 007 Mercedes**
假设我想在其他变量中使用这个方法
var car1 = car.displayDetails('Nishant');car1(); // undefined
要在其他变量中使用car的引用,您应该使用
var car1 = car.displayDetails.bind(car, 'Nishant');car1(); // Nishant this is your car 007 Mercedes
让我们来谈谈bind函数的更广泛的使用
var func = function() {console.log(this)}.bind(1);
func();// Number: 1
为什么?因为现在func与数字1绑定,如果我们在这种情况下不使用绑定,它将指向全局对象。
var func = function() {console.log(this)}.bind({});
func();// Object
当您想同时执行语句时,可以使用Call、Ap唱。
var Name = {work: "SSE",age: "25"}
function displayDetails(ownerName) {console.log(ownerName + ", this is your name: " + 'age' + this.age + " " + 'work' + this.work);}displayDetails.call(Name, 'Nishant')// Nishant, this is your name: age25 workSSE
// In apply we pass an array of argumentsdisplayDetails.apply(Name, ['Nishant'])// Nishant, this is your name: age25 workSSE
var obj = {name: "Raushan"};
var greeting = function(a,b,c) {return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;};
console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
应用():--这里我们以数组格式传递函数参数
var obj = {name: "Raushan"};
var cal = function(a,b,c) {return this.name +" you got " + a+b+c;};
var arr =[1,2,3]; // array format for function argumentsconsole.log(cal.apply(obj, arr));
bind():--
var obj = {name: "Raushan"};
var cal = function(a,b,c) {return this.name +" you got " + a+b+c;};
var calc = cal.bind(obj);console.log(calc(2,3,4));