search
HomeWeb Front-endJS TutorialJavaScript Advanced Programming Extension--About Dynamic Prototype_Javascript Skills

However, the author Nicholas C. Zakas did not delve into the possible problems and solutions when creating objects using the [Dynamic Prototype] method. But only the bottleneck of [dynamic prototype] is explained during inheritance. That is, when subclass inheritance is performed, it cannot be achieved through dynamic prototypes.
The original text is roughly as follows:
The reason why the inheritance mechanism cannot be dynamic is: the uniqueness of the prototype object. Example code:

Copy code The code is as follows:

function A (i) {
this.a = i;
if (typeof A._init == 'undefined') {
A.prototype.func = function () {
return 0;
}
A. _init = 1;
}
}
function subA (j) {
A.call(this, 1);
this.j = j;
if (typeof subA. _init == 'undefined') {
subA.prototype = new A();
subA.prototype.func_sub = function () {
return j;
}
subA._init = 1;
}
}
var sub_a = new subA(1);
alert(sub_a.func_sub()); //error: sub_a.func_sub is not a function

Nicholas explained that before the code is run, the object has been instantiated and contacted with the prototype. Replacing the prototype object at the current time will not have any impact on it, that is, the current replacement is inaccessible, only the future object. Examples will reflect this change. Then the first instance object will be incorrect. But the second and subsequent subclass instances are fine.
The solution is to assign a new prototype object outside the constructor:
Copy the code The code is as follows:

function A (i) {
this.a = i;
if (typeof A._init == 'undefined') {
A.prototype.func = function () {
return 0;
}
A._init = 1;
}
}
function subA (j) {
A.call(this, 1);
this .j = j;
if (typeof subA._init == 'undefined') {
subA.prototype.func_sub = function () {
return j;
}
subA._init = 1;
}
}
subA.prototype = new A();
var sub_a = new subA(1);
alert(sub_a.func_sub()); //2

Unfortunately this defeats the purpose of why we use dynamic prototypes.
The original intention of using dynamic prototypes is to allow the constructor to "unify the country" and visually make people feel that the prototype method is part of the class construction.
The above is the general content of the dynamic prototype inheritance section in "Advanced JavaScript Programming".

But Nicholas talked about object construction in the previous chapter [ Dynamic prototype] approach, it seems that the same issue was forgotten. Let’s look at the last example above:
Copy the code The code is as follows:

var Obj = function (name) {
this.name = name;
this.flag = new Array('A', 'B');
if (typeof Obj._init == 'undefined') {
Obj.prototype = {
showName : function () {
alert(this.name);
}
};
Obj._init = true;
}
}
var obj1 = new Obj('aa');
var obj2 = new Obj('bb');
obj1.showName(); //error: is not a function
obj2.showName(); // bb;

Yes, this problem is actually the same as the problem that occurs in subclass inheritance. The current replacement of prototype will not have any impact on the object. , visible only in future instances. If you follow the way Nicholas handles dynamic prototypal inheritance, it means that the prototype object can only be reassigned outside the constructor. So doesn’t this become the [constructor/prototype hybrid] method? The so-called [dynamic prototype] method no longer exists...

In fact, we can think about why [constructor/prototype hybrid], a method of building objects that has basically no side effects, is followed by Write a section on [Dynamic Prototyping] method. Is the author's intention nothing more than to make the constructors more visually unified? In fact, dynamic prototypes are not needed as long as visual unity is required.
Copy code The code is as follows:

var Obj = function () {
function __initialize (name) {
this.name = name;
this.flag = new Array('A', 'B');
}
__initialize.prototype = {
showName : function () {
alert(this.name);
},
showFlag : function () {
alert(this.flag);
}
}
return __initialize ;
}();
var obj1 = new Obj('aa');
var obj2 = new Obj('bb');
obj1.showName(); // aa
obj2.showName(); // bb

In fact, the above method can be regarded as visual unification. The properties are initialized through __initialize in the constructor of Obj, and the __initialize.prototype prototype initialization method is used. It just feels like a little "cheating". __initialize represents the initialization of Obj...
The following is the encapsulation of the "constructed class" from tangoboy. In fact, the idea is basically the same as the above. The only difference is that he also adds attributes It was created in prototype mode, and the initialization properties and methods were thrown into the constructor parameter object. Easy to customize:
Copy code The code is as follows:

/* == form tangoboy == */
window['$Class'] = {
//Create a class with mixed constructor/prototype method
create: function(config) {
var obj = function(){}, config = config||{};
//Filter constructor and prototype methods
obj = obj.prototype.constructor = config["__"]||obj;
delete config["__"] ;
obj.prototype = config;
return obj;
}
}
/* -- eg -- */
var man = $Class.create({
__ : function (name) {
this.name = name;
},
sex : 'male',
showName : function () {
alert(this.name);
}
});
var me = new man('ru');
me.showName(); //ru

In fact, if you insist on pursuing Visual unification can also be achieved without dynamic prototyping. After all, looking at the above ideas, we have traced back to our most commonly used "class construction" method:
Copy code The code is as follows:

var Class = {
create : function () {
return function () {
this.initialize.apply(this, arguments);
}
}
}

I believe that the above code may be familiar to everyone. If you study it carefully, you will find that it is actually consistent with the above code. The initialize function is used as the initialization agent. Thus completing the visual unity.
Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft