search
HomeWeb Front-endJS TutorialJavaScript constructor and instanceof, a pair of happy enemies in JSOO_javascript skills

At least every programmer who tries JavaScriptOO spends a lot of energy on the simulation of the object-oriented mechanism rather than the business itself.
This is unimaginable for developers of Java, C and even Php.
More The bad thing is that simulating OO has an evil attraction for advanced JavaScript programmers.
Because doing this thing is transcendent from business, there is a kind of pleasure of creating a new programming language, which can make your IQ flourish.
Just like In the past few years, everyone wanted to write the common.js of their website as a framework. It was not until the strong launch of YUI, JQuery, etc. that it calmed down a little.
However, although each framework has JavaScriptOO simulation, it has not yet arrived. When someone can make a bucket of paste.
Maybe there will be no unnecessary overlord in the world, or everyone just needs to wait until JS2.0.
If new means object-oriented, then obviously JavaScript is here The aspect is very good.

Copy code The code is as follows:

function Person(name){
this.name = name;
}
var lenel = new person("lenel");
alert(lenel.constructor === Person);
alert(lenel instanceof Person = == true);
alert(lenel instanceof Object === true);

So far, everything is harmonious.
The constructor of the object points to the constructor literally. Its Person.
The object is an instance of the Person that constructed it.
All objects are instances of Object, just like Java.
JavaScript provides a prototype way to implement methods Extension and inheritance
Copy code The code is as follows:

Person.prototype.getName = function() {
return this.name
};

After this definition, all objects have the getName method.
Of course, it can also be written in the object construction
Copy code The code is as follows:

function Person(name){
this.name = name;
this.getName = function(){
return this.name;
};
}

But this approach not only brings additional performance loss The flaw is not only the privilege of accessing private variables.
It is also different from the way of writing using prototype, but this is not the focus of this article.
Next, we think of inheritance, which is very The common way to write it is like this.
Copy code The code is as follows:

function Stuff(name, id){
this.name = name;
this.id = id;
}
Stuff.prototype = new Person();
var piupiu = new Stuff("piupiu", "007");
alert(piupiu.getName());

Very good, it inherits the getName method;
Check instanceof
Copy code The code is as follows:

alert(piupiu instanceof Stuff === true);
alert(piupiu instanceof Person === true);

Very good, it shows that Stuff and Person are related. piupiu is an instance of them, very Java.
Let’s examine the constructor
Copy code The code is as follows:

alert(piupiu.constructor === Stuff);//false
test (piupiu.constructor === Person);//true

The question arises why the constructor of new Stuff is Person.
The reason here is also unreasonable, we have to remember Conclusion
Conclusion: The constructor attribute of an object does not point to its constructor, but the constructor attribute of the prototype attribute of its constructor
My writing skills are so poor that I didn’t think it was clear even after I read it
Put it here :
The constructor property of the object piupiu points to the constructor property of the prototype property of its constructor Stuff
Because Stuff.prototype = new Person();
So Stuff.prototype.constructor === Person.
So piupiu.consturctor === Person.
The above conclusion does not only appear when objects are inherited, but also when defining objects
Copy code The code is as follows:

function Student(name){
this.name = name;
}
Student.prototype = {
getName :function(){
return this.name;
},
setName:function(name){
this.name = name;
}
}

메서드가 많으면 이렇게 작성하는 경우가 더 규칙적으로 보입니다.
실제로 이런 작성 방식은 생성자를 희생하기도 합니다
코드 복사 코드는 다음과 같습니다.

var moen = new Student("moen")
alert(moen.constructor === Student) ;//false
alert( moen.constructor === Object);//true

{}는 new Object()와 동일하므로 위 결론에 따르면 프로토타입이 ={}, 생성자가 변경됩니다.
생성자를 보호합니다! 상속 시 루프를 사용하여 상위 클래스의 메서드를 하위 클래스에 복사합니다.
코드 복사 코드는 다음과 같습니다.

function Stuff1(name,id){
this.name = name; >}
for(var fn in Person.prototype){
Stuff1.prototype[fn] = Person.prototype[fn];
}
var piupiu1 = new Stuff1("piupiu1"," 008");
alert(piupiu1.getName() == = "piupiu1");
alert(piupiu1.constructor === Stuff1);


작동합니다! 행복하게 부모 클래스의 모든 메서드를 상속받으면 부모-자식 관계가 끊어집니다.


alert(piupiu1 인스턴스of Stuff1 == = true);//true
alert(piupiu1 인스턴스of Person === true);//false


분명히 Stuff1이 Person으로부터 상속받았다고 말하지 않았는데, for 루프만 있다는 게 무슨 뜻일까요?
이것은 모순인 것 같습니다.
그래서. , 객체를 깊이있게 사용하면 조심하지 않아도 instantceof와 생성자가 문자 그대로의 의미를 잃게 됩니다.
따라서 프레임워크를 사용할 때 상속 기능이 제공되면 어떤 것을 사용하는지 알 수 없습니다.
그래서 OO를 시뮬레이션할 때는 이 두 리터럴에 대한 대안을 제공해야 합니다.
OO를 시뮬레이션하려면 속성이나 메서드 구현의 의미를 알아야 합니다. 이는 확실히 이 문제에 국한되지 않습니다. 하위 클래스 메서드에서 동일한 이름으로 부모 클래스의 메서드를 호출하는 것은 OO 언어의 일반적인 기능입니다.
JS도 기본적으로 매우 어렵습니다. 그러나 Base 라이브러리와 같이 신중하게 수행하면 사용하기가 더 자연스럽습니다.
물론, instanceof 및 생성자의 사용을 포기할 수 있으며, 그런 것이 있다는 것을 알면 됩니다. 그래도 일은 계속할 수 있고 아무도 죽지 않을 것입니다.
그러나 혼자 싸우는 것이 아니라면 파트너에게 이 두 명의 적들을 버리라고 알리십시오.
오늘의 요점과 유사하게 참전용사들은 이것을 잘 알고 있습니다. 그러나 팀의 모든 사람이 통일된 이해를 갖고 있지 않다면
흥미로운 현상은> 을 강조하고 > 그리고 둘은 서로를 그냥 무시하거나 전혀 언급하지 않습니다. 그 원한은 매우 깊습니다.
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: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.