You might have read these stuff so many times and I am writing this in December of 2015 which is quite a bit late. What I am going to share today are some basic but essential to anyone's javascript knowledge. Well, we must know that Javascript itself creates a global object, that is window. Whatever function we make becomes a method for the window object. Therefore each time we use keyword `this` can refers to the window object.
The call, apply and bind are some native methods to point `this` to our desired object. Each method has its browser support and uses. This post would be sharing all of these. You should read my Javascript's basic knowledge, here are some of them:
The call, apply and bind are some native methods to point `this` to our desired object. Each method has its browser support and uses. This post would be sharing all of these. You should read my Javascript's basic knowledge, here are some of them:
- Glance over Javascript's Object Oriented behaviour
- Javascript Closure and nested function
- Memory leaks and memory management in Javascript
Bind method
var baby = {
  name: 'Muhammad Ali',
  age: '1 year'
}
// Creating a local baby object below
var hospital = {
  baby: {
    name: 'Saad',
    age: '2 year'
  },
  getBaby: function(e) {
      console.log('This is ' + this.baby.name + ' and he is ' + this.baby.age + ' old')
    }
}
var currentBaby = hospital.getBaby;
currentBaby(); // This is Muhammad Ali and he is 1 year old
var currentBaby = hospital.getBaby.bind(hospital);
currentBaby(); // This is Saad and he is 2 year old`this` in basic function
The basic concept of `this` should remain same. But what if we are taking about just a simple function with keyword `this`, well its simply that `window` object.
function hello(){
console.log(this)
}
hello(); //window{}function hello(anyArg){
console.log(this + " says hello " +anyArg)
}
hello.call('Hamza','World') // Hamza says hello WorldDon't confuse it with $(this)
jQuery's $(this) is different from `this` in native Javascript. 
- `this` targets the DOM element.
- $(this) are jQuery objects, can be used only in jQuery
Apply and call method
Apply and call methods are same just the difference is:
- arguments are passed as individual in call method
- arguments are passed as array in apply
var numbers=[1,2,3,4,5];
console.log(Math.max.apply(null,numbers)); // 5
console.log(Math.max.call(null,4,5,6,7)); // 7var students = [{
  name: 'Muhammad Ali',
  class: '5'
}, {
  name: 'Sara',
  class: '6'
}, {
  name: 'Saad',
  class: '7'
}];
for (var i = 0; i < students.length; i++) {
  (function(s){
    var d=s+1;
    console.log('Number '+d+': '+this.name+ ' ('+this.class+')');
  }).call(students[i],i);
}
// Number 1: Muhammad Ali (5)
// Number 2: Sara (6)
// Number 3: Saad (7)

 

Post A Comment:
0 comments: