JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Object4

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