Skip to main content
0:00est. 5 min

Chapter 56- Reflection and Extend

Notes

#BIGWORD Reflection : An object can look at itself, listing and changing its properties and methods. It can be used to create very useful pattern extend.
Example 1 :
var person = {
firstname: ‘Default',
lastname: ‘Default',
getFullName: function(){
return this.firstname + " " + this.lastname;
}
};

var john = {
firstname : ‘John',
lastname : ‘Doe'
}

//don't do this EVER, for demo purpose only!!!
john.__proto__ = person;


//For-in to loop over every property in object
for(var prop in john){
console.log(prop + " : " + john[prop]);
}

//OUTPUT Getting all properties of itself and inherited
firstname : ‘John'
lastname : ‘Doe'
getFullName: function(){
return this.firstname + " " + this.lastname;
}

Example 2 :
//Check what properties are owned by object itself
for(var prop in john){
if(john.hasOwnProperty(prop)){
console.log(prop + " : " + john[prop]);
}
}
//OUTPUT Getting all properties of itself
firstname : ‘John'
lastname : ‘Doe'

Example 3:
var jane = {
address : ‘111 Main St.',
getFormalFullName: function(){
return this.lastname + " ," + this.firstname;
}
}

var jim = {
getFirstName : function(){
return this.firstname;
}
}
//underscorejs function
_.extend(john,jane,jim);