The new keyword in JavaScript can be instantiated and inherited, but the individual believes that using the New keyword is not the best practice and can have a more user-friendly implementation. This article describes what is wrong with the new keyword, and then describes how to encapsulate a series of object-oriented operations associated with new to provide a faster and more understandable implementation.
Traditional instantiation and inheritance
Suppose we have two classes, Class:function class () {} and Subclass:function subclass () {},subclass need to inherit from class. Traditional methods are generally organized and implemented in the following steps:
Attributes and methods that are inherited in class must be placed in the prototype property of class
Your own methods and properties in subclass must also be placed in your own prototype properties
The prototype (__proto__) attribute of the subclass prototype object must point to the prototype of the class
Thus, because of the characteristics of the prototype chain, an instance of subclass can be traced back to the method of class to achieve inheritance:
New Subclass () object.create (class.prototype)
| |
V v
subclass.prototype---> {}
{}.__proto__---> class.prototype
To give a concrete example: in the following code, we do the following things:
Define a parent class called human
Define a subclass named man to inherit from human
The subclass inherits all of the attributes of the parent class and invokes the constructor of the parent class, instantiating the child class
Constructor/base class
function Human (name) {
this.name = name;
}
/* The method of the base class is saved in the prototype property of the constructor to
facilitate inheritance of subclasses
/Human.prototype.say = function () {
Console.log ("Say") ;
}
/* Douglas Object Method (equivalent to Object.create method)
/
function Object (o) {
var F = function () {};
F.prototype = O;
return new F ();
}
Subclass constructor Function Man
(name, age) {
//Call the constructor of the parent class
Human.call (this, name);
Own attribute age
this.age = age;
}
The method that inherits the parent class
Man.prototype = Object (human.prototype);
Man.prototype.constructor = Mans;
Instantiate subclass var man
= new Man ("Lee");
Console.log (mans);
Invoke the Say method of the parent class:
Man.say ();
DEMO
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/