javascript this

window.name = "Window Doe";
var globalGreet = function() {
  return "My name is " + this.name; // this refers to window
};
console.log( globalGreet() ); // returns 'My name is Window Doe'
 
 
var johnDoe = {
  name : "John Doe",
  greet : globalGreet
};
console.log( johnDoe.greet() ); // returns 'My name is John Doe'
 
 
var person = {
  name : "John Doe",
  greet : function() {
   return "Hi there " + this.name; // this refers to person
  }
};
console.log( person.greet() ); // returns 'My name is John Doe'
 
 
var bindDoe = {
  name : "Bind Doe",
  greet : window.globalGreet.bind(window)
};
console.log( bindDoe.greet() ); // returns 'My name is Window Doe'

Example:

var makeRequest = function(url, callback) {
  // make the request with the provided url
  var data = 10; // json text xml
  callback(data);
};
 
var obj = {
  someValue : 20,
  loadData : function(data) {
    var sum = this.someValue + data;
    alert(sum); // alerts '30'
  },
  prepareRequest : function() {
    var url = "http://numberservice.com";
    makeRequest(url, this.loadData.bind(this));
  }
};

Leave a Reply

Your email address will not be published. Required fields are marked *