#5-53 Classical vs prototypal ingeritance

bigword alert : Inheritance

  • one object gets access to the properties and methods of another object

#5-54 Understanding Prototype

  • every object in js has a property called proto
  • proto is a object too.
  • js engine do the search in prototype chain for the properties and methods
  • this in __proto__ point to the origin object, not the __proto__ object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

var person = {
firstname : 'Default',
lastname : 'Default',
getFullName : function(){
return this.firstname + ' ' + this.lastname;
}
}

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

var jane = {
firstname : 'Jane'
}

// don't do this EVER! for demo purposes only!!
// performance issue
john.__proto__ = person;
jane.__proto__ = person;
console.log(john.getFullName());
console.log(john.firstname);
console.log(jane.getFullName);

#5-55 Every things is an object(or a primitive)

  • all thing has __proto__, except basic object
  • Object is the bottom of prototype chain
1
2
3
4
5
6
7
8

var a = {};
var b = function(){};
var c = [];

a.__proto__ //object{}
b.__proto__ //Empty(){}
c.__proto__ //[]

#5-56 Reflection and Extend

bigword alert : Reflection

  • an object can look at itself, listing and changing its properties and methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

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 purposes only!!
john.__proto__ = person;

for(var prop in john){
console.log(prop + ' : ' + john[prop]);//show all properties including proto's
//use object.hasOwnProperty to check
}
underscore extend
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// require underscore

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

var jane = {
address : '111 Main St.';
getformalFullName : function (){
return this.lastname + ', ' + this.firstname;
}
}

var jim = {
getFirstName : function(){
return firstname;
}
}

_.extend(john, jane, jim);
console.log(john);
source code of _
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);

// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};