stuart-d2
1/6/2015 - 11:21 AM

Knight and Warlord Javascript Object Summary Play : create prototype base class object, then use object.create to create a regular instanc

Knight and Warlord Javascript Object Summary Play :
create prototype base class object, then use object.create to create a regular instance, then creeate a instance that overrides function/properties of prototype object, then use the call/apply/bind functions for correct scoping.


		 // the prototype object 
		function Hero(type)  {
		        //properties of this proto object
		        this.strength = 0;
		        this.type = type || "No type"; 
		        }
		        
		        // proto function, used by all 
		        Hero.prototype.attack =  function(newStrength) {
		                this.strength = newStrength;
		        }
		        
		        this.func = function () {
		               return this.type;  
		        }
		        
		}
		//new object instance
		var knight = new Hero("Knight");
		console.log(knight.strength);  // outputs 0 
		console.log(knight.type); // outputs "Knight"
		knight.attack(25);  
		
		//strength is now set to 25.  
		console.log((knight.strength); //outputs 25
		
		// MONO instance, warlord is stronger
		var warlord = new Hero("Warlord"); 
		warlord.attack = function(newStrength) {
		        this.strength = newStrength + 10;  
		}  
		
		console.log(knight.strength);  
		console.log(warlord.strength); 
		
		//making attack a function -- usually this would cause trouble with the this keyword and correct contexting, but this is alleviated by the call, apply bind functions 
		var attackFunc = knight.func;
		console.log(func.call(knight)); 
		console.log(func.apply(knight));
		
		// or the bind way
		var func = knight.func.bind(bmw); 
		console.log(func());