Tuesday, 23 June 2015

javascript basic again -- object


example: 

var Pet = function(){
   this.ears = 2;    // this here is different, it is the reference of current instance.  (the runing Pet instance.)
}

var kitten = new Pet();
alert(kitten.ears)     //return 2

------
prototypes:

"The prototype property allows you to add properties and methods to an object."

var Pet = function(){
   this.ears = 2;    // this here is different, it is the reference of current instance.  (the runing Pet instance.)
}
Pet.prototype.ears = 6

var kitten = new Pet();

Pet.prototypes.ears  /// is used to modify the defination of a class, so it will be applied when use call new xxx();


--
var Pet = function(){
   this.ears = 2;    // this here is different, it is the reference of current instance.  (the runing Pet instance.)
}
Pet.prototype.ears = 6

var kitten = new Pet();

alert(kitten.ears)     //return 6

However, examples above return "2" not "6". Because "ears" is a existing property. prototype can not override it.

Second, even Pet don't have ears. changing prototype before or after new Pet() doesn't make any differents.  "kitten" will get it by anyway.

--
but:

var Pet = function(){
   this.ears = 2;    // this here is different, it is the reference of current instance.  (the runing Pet instance.)
}

var kitten = new Pet();

Pet.prototype.ears = 6

alert(kitten.ears)     //return 2


----------
Inherit




var Pet = function(){
   this.ears = 2;    // this here is different, it is the reference of current instance.  (the runing Pet instance.)
}

var kitten = new Pet();
Pet.prototypes.ears = 6
var Dog = function){}

Dog.prototyes = new Pet();  // this line makes Dog inherits  Pet, but actually Dog only inherits Pet's prototypes.
var puppy = new Dog();
alert(puppy.ears)

This code will alert 2, as dog inherits 2 ears from Pet.


Note: what I said above is wrong. Because, first, ears is an existing property in Pet, so "ears" of "puppy" and "kitten" are all "2". Second, Dog inherits from Pet, not Pet's prototype. When you call a property or a function from "puppy", it will find them from Dog first and then check Dog's prototype and then check from  Pet, then check in Pet's prototype.     So, keep in mind: prototype only allows you add new properties!!!!!

When you do "Dog.prototype=new Pet()" that copies all Pet's properties and Pet prototype's properties into Dog's prototype. (when I say Pet's and Pet prototype's properties that means properties we can see from Pet.<Pet's properties has higher priority> ).

Dog.prototype = new Pet();

Dog.prototype.ears = 9; // this line above or after do make different. that does not like when we create "puppy". Because "Dog.prototype = new Pet();" does the copy, and "Dog.prototype.ears = 9;" is kinds of copy as well, who do first who will be override by later copy.
























No comments:

Post a comment