Create objects and inherit sample interpretations in JavaScript

  • 2020-03-30 01:43:19
  • OfStack

Object creation:

When a Function object is created, the Function object generated by the Function constructor runs something like this:
 
this.prototype={constructor:this}; 

Suppose the function F
When F constructs an object in new mode, the constructor for the object is set to this f.prototype.constructor
If the function before the object creation changed the function prototype, affect created construtor attributes of objects

Such as:
 
function F(){}; 
F.prototype={constructor:'1111'}; 
var o=new F();//o.constructor=== ' 1111' true 

Principle of inheritance:

Inheritance in JavaScript is a mechanism that USES a prototype chain. Each instance of a function shares the data defined in the constructor prototype property. And each time the new instance object, the private property of the object is automatically connected to the constructor's prototype.

Instanceof simply looks up the private prototype property chain of the instance object to see if it is an instanceof the specified object

Specific examples:
 
//Instanceof implementation
function Myinstanceof(obj,type) 
{ 
var proto=obj.__proto__; 
while(proto) 
{ 
if(proto ===type.prototype)break; 
proto=proto.__proto__; 
} 
return proto!=null; 
} 


function View(){} 
function TreeView(){} 
TreeView.prototype=new View();//Prototype. s = treeview.prototype auto complete
TreeView.prototype.constructor=TreeView;//Fixed the constructor
var view=new TreeView();//View.s/s/s/s/s = treeview.prototype auto complete
alert(view instanceof View); //Found when true finds view.s. S. S. S. S. S. S. S. S. S
alert(view instanceof TreeView); //Found when true finds view.slower
alert(Myinstanceof(view,View)); //true 
alert(Myinstanceof(view,TreeView)); //true 

Related articles: