stuart-d2
1/4/2015 - 3:23 PM

this Keyword Correct Contexting Functions : Apply, Call and Bind call, apply and bind are ways to override the difficulties with the this k

this Keyword Correct Contexting Functions : Apply, Call and Bind call, apply and bind are ways to override the difficulties with the this keyword and context. bind doesn’t work well with legacy browsers, so if you are developing for IE8 etc, use the apply and call functions.


	function Car(type) {
	        this.type = type;
	        this.speed = 0;
	        this.func = function() { 
	                return this.type;
	                }
	}
	
	var bmw = new Car("BMW");
	var func = bmw.func;
	console.log(func.call(bmw)); // outputs BMW
	console.log(func.apply(bmw));  // outputs BMW

// the bind function 

		 function Car(type)
		        this.type = type; 
		        this.speed = 0;
		        this.func = function() {
		                return this.type;
		        } 
		}
		
		var bmw = new Car("BMW"); 
		var func = bmw.func.bind(bmw);  
		console.log(func()); // outputs BMW