JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Week 8 16 Bind 1

		
001this.x = 9;    // 'this' refers to global 'window' object here in a browser
		
002
		
003const moduleObject1 = 
		
004{
		
005  x: 81,
		
006  getX: function() { 
		
007	return this.x; // this 'this' refers to the function
		
008	}
		
009};
		
010
		
011const moduleObject2 = 
		
012{
		
013    x: 90,
		
014	getX: function() { 
		
015		return this.x; 
		
016	}
		
017};
		
018  
		
019 
		
020// point the retrieveX variable to the function
		
021const retrieveX = moduleObject1.getX;
		
022// Run the function you just copied
		
023console.log('logging retrieveX():');
		
024console.log(retrieveX());
		
025//  logs 9; the function gets invoked at the global scope
		
026// Why it logs 9; We want it to return 81
		
027
		
028// bind the boundGetX variable to the 1st object and function
		
029const boundGetX = retrieveX.bind(moduleObject1);
		
030console.log('logging boundGetX():');
		
031console.log(boundGetX());
		
032//  logs 81 
		
033
		
034// bind the 2nd object to the function
		
035const boundGetX2 = retrieveX.bind(moduleObject2);
		
036console.log('logging boundGetX2():');
		
037console.log(boundGetX2());
		
038// logs 90
		
039