Prototype chain:
Object (constructor) object (Type (object))
var o = {};alert (typeof/ / result is Objectalert (typeof// The result is function
Each object has a property called __proto__, which is the prototype of this object (O. __PROTO__),
Functions can be obtained through the function name. prototype gets the prototype, and the object can be retrieved through the object. __PROTO__ (double underscore).
Objects have prototypes, prototypes are objects, so prototypes have prototypes, and all functions are objects, inherited from Function.prototype,
Function.prototype is an object that inherits from Object.prototype,object.prototype is an object and inherits from null.
Obj is an object that inherits from Object.prototype
function is an object, inherited from Function.prototype
function is functions, inherits from Function.prototype
Access rules for JS members:
O. Method ()
First, look for the definition of the member in the current type O, and if there is a definition of the member, use the change member directly;
If the member is no longer in the current type, it accesses its prototype (the previous level in the prototype chain) and so on, until the null position.
code example:
Do not use inheritance:
var function () {thisfunction() {alert ("Hello");};} ; var New Person (); var New // result is false
Each new object creates a piece of memory, so P1.say and P2.say are not the same address as the reference.
Using prototype inheritance:
var function = {say:function() {alert ("Mr Jing");}}; var New Person (); var New = "Mr Jing"= = = = P2.say); // The result is truealert (p2.name); // The result is "Mr Jing"
To emulate a class in C #:
varo ={say:function() {Alert ("Hello, I am" + This. Name + ", I am this year" + This. Age + "old, I am" + This. Sex + "Live");},get_name:function() {return This. Name;},set_name:function(value) { This. Name =value;}};varperson =function(name,age,sex) { This. Name =name; This. Age =Age ; This. Sex =sex;}; Person.prototype= O;//similar to having the person class inherit the parent class OvarP1 =NewPerson ("Mr Jing", 19, "male");p 1.say ();
General approach to inheritance:
var function (name) {this. Name = name;}; var o = {sayHello:function() {alert ("Hello, I am" + (this. name| | " Non-existent"// function inherit in this.name=name equivalent to adding the name attribute to object o and assigning" Mr Jing "to it O.sayhello (); alert (o.name);
JS prototype inheritance