JAVA SCRIPT - Rediscovering this with Prototype.bind - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Rediscovering this with Prototype.bind - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, December 27, 2018

JAVA SCRIPT - Rediscovering this with Prototype.bind

Rediscovering this with Prototype bind


Problem

You want to control the scope assigned a given function. 

Solution

Use the bind() method:
window.onload=function() {
 window.name = "window";
 var newObject = {
 name: "object",
 sayGreeting: function() {
 alert("Now this is easy, " + this.name);
 nestedGreeting = function(greeting) {
 alert(greeting + " " + this.name);
 }.bind(this);
 nestedGreeting("hello");
 }
 };
 newObject.sayGreeting("hello");
};


EXPLAIN


 this represents the owner or scope of the function. The challenge associated with this in JavaScript libraries is that we can’t guarantee which scope applies to a function. In the solution, the object has a method, sayGreeting(), which outputs a message and maps another nested function to its property, nestedGreeting.

Without the Function’s bind() method, the first message printed out would say, “Now this is easy, object”, but the second would say, “hello window”. The reason the second printout references a different name is that the nesting of the function disassociates the inner function from the surrounding object, and all unscoped functions automatically become the property of the window object.

What the bind() method does is use the apply() method to bind the function to the object passed to the object. In the example, the bind() method is invoked on the nested function, binding it with the parent object using the apply() method. bind() is particularly useful for timers, such as setInterval().

web page with a script that uses setTimeout() to perform a countdown operation, from 10 to 0. As the numbers are counted down, they’re inserted into the web page using the element’s innerHTML property.

 Demonstrating the utility of bind

If the setTimeout() function in the code sample had been the following:
setTimeout(this.countDown, 1000);

self = this An alternative to using bind(), and one that is still in popular use, is to assign this to a variable in the outer function, which is then accessible to the inner. Typically this is assigned to a variable named that or self:

window.onload=function() {
 window.name = "window";
 var newObject = {
 name: "object",
 sayGreeting: function() {
 var self = this;
 alert("Now this is easy, " + this.name);
 nestedGreeting = function(greeting) {
 alert(greeting + " " + self.name);
 };
 nestedGreeting("hello");
 }
 };
 newObject.sayGreeting("hello");
};


Without the assignment, the second message would reference “window”, not “object”

No comments:

Post a Comment

Post Top Ad