Detailed creation of JS prototype object
- 2021-06-28 10:54:26
- OfStack
This article gives an example of how to create an JS prototype object.Share it for your reference, as follows:
When using the prototype property of js, there is a priority in how objects are created
1. If there is a construction method in the method, use the construction method in the method first.
2. Continue to find the construction method of the prototype prototype if there is no construction method in the method
<html>
<head>
<TITLE>class_obj_js_class</TITLE>
<script language=javaScript>
function a(name){
//alert(name);// The pop-up value is undefined
//alert(null==name);//true
if(null == name){
this.name = name;
}
}
function b(name){
//alert(name);// The pop-up value is undefined
//false,this.name Didn't reassign, or new Created value prototype.name="TOm"
if(null != name){
this.name = name;
}
}
// Parametric construction method
function c(name){
//alert(name);// The pop-up value is undefined
// If name by true Then go back to No matter what follows 1 Values
// If name by false Returns the following value directly, regardless of what follows
this.name = name || "Jack";// If name Empty assigns the following Jack
}
// Parameterless construction method
function d(){
}
a.prototype.name = "Tom";
b.prototype.name = "Tom";
c.prototype.name = "Tom";
d.prototype.name = "Tom";
// Parametric construction method
alert(new a().name); //undefined
alert(new b().name);//Tom
alert(new c().name);//Jack
alert(new d().name);// Use parameterless construction method
</script>
<body >
</body>
</html>
Remarks:
1.1 Normally we add an attribute of "object" to the method
2. Add a method after the prototype attribute
This is done to improve code reuse by "infinitely" adding methods to objects for easy expansion
Note: In order to improve the efficiency of JS, it is important to note that the prototype chain should be reused at level 1.2 as the browser will automatically de-cycle traversal, which will affect efficiency if the depth is too deep
More readers interested in JavaScript-related content can view this site's topics: Summary of JavaScript Switching Effects and Techniques, Summary of JavaScript Finding Algorithmic Techniques, Summary of JavaScript Animation Effects and Techniques, Summary of JavaScript Errors and Debugging Techniques, Summary of JavaScript Data Structure and Algorithmic Techniques.Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage
I hope that the description in this paper will be helpful to everyone's JavaScript program design.