Home > Web Front-end > JS Tutorial > body text

Principles of object creation and inheritance in JavaScript

高洛峰
Release: 2016-11-28 15:51:01
Original
1039 people have browsed it

Object creation:

When a function object is created, the function object generated by the Function constructor will run code similar to this:
this.prototype={constructor:this};
Suppose function F
F constructs the object using new method When the object's constructor is set to this F.prototype.constructor
If the function modifies the prototype of the function before creating the object, it will affect the constructor attribute of the created object
For example:

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

Inheritance principle:

Inheritance in JavaScript uses the mechanism of the prototype chain, each Instances of each function share the data defined in the prototype attribute of the constructor. To make one class inherit another, you need to assign the parent function instance to the prototype attribute of the child function. And every time a new instance object is created, the object's private property __proto__ will be automatically connected to the prototype of the constructor.

instanceof is to find the private prototype attribute chain of the instance object to determine whether it is an instance of the specified object


Specific example:
//instanceof implementation
function Myinstanceof(obj,type)
{
var proto=obj.__proto__;
while(proto)
                                                                                                                                                                                                                                              if (proto === type.prototype) break; ){}
TreeView.prototype=new View();//TreeView.prototype.__proto__=TreeView.prototype automatically completed
TreeView.prototype.constructor=TreeView;//Correction constructor
var view=new TreeView();// view.__proto__=TreeView.prototype is automatically completed
alert(view instanceof View); //true is found when view.__proto__.__proto__ is found
alert(view instanceof TreeView); //true is found when view.__proto__ is found

alert(Myinstanceof(view,View)); //true

alert(Myinstanceof(view,TreeView)); //true
The customized Myinstanceof above is a function of instanceof function implemented by myself. Since the IE kernel instance storage prototype is not __proto__, so Myinstanceof will not pass. There should be no problem on other browsers



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template