search
HomeWeb Front-endJS TutorialWhat are the two forms of javascript inheritance?

What are the two forms of javascript inheritance?

Apr 08, 2021 pm 02:16 PM
javascriptinherit

Javascript inheritance has two forms: "object impersonation" and "prototype mode". The essence of object impersonation is to change the point of this; and prototype inheritance refers to using prototype or overriding prototype in some way, so as to achieve the purpose of copying attribute methods.

What are the two forms of javascript inheritance?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript itself evolved from the syntax of the Perl language. It is essentially a scripting language. As the version is updated, object-oriented simulation is gradually added.

I think the object-oriented simulation of Js is generally good, because we can't blindly follow any concept, and we can't do OOP purely for the sake of OOP. What we need to grasp is the benefits of object-oriented. What? Going to OOP for these advantages is the wisest choice, so Js is doing pretty well.

Js inheritance is carefully divided into many types and implementation methods in many books. There are generally two types: object impersonation and prototype method. Each of these two methods has its advantages and disadvantages. I will list them here first, and then analyze the differences from the bottom level:

(1) Object impersonation

function A(name){
this.name = name;
this.sayHello = function(){alert(this.name+” say Hello!”);};
}
function B(name,id){
this.temp = A;
this.temp(name); //相当于new A();
delete this.temp; //防止在以后通过temp引用覆盖超类A的属性和方法
this.id = id;
this.checkId = function(ID){alert(this.id==ID)};
}

When When constructing object B, calling temp is equivalent to starting the constructor of A. Note that the this object in the context here is an instance of B, so when the A constructor script is executed, all A's variables and methods will be assigned to this. The object it refers to is an instance of B. In this way, the purpose of B inheriting the attribute methods of A is achieved.

After deleting the temporary reference temp, it is to prevent the maintenance of the reference change to the class object of A (note that it is not an instance object) in B, because changing temp will directly cause the structure of class A (note that it is not an object of class A) Variety.

We have seen that in the process of updating the Js version, in order to more conveniently perform this context switching to achieve inheritance or broader purposes, the call and apply functions were added. Their principles are the same, just different versions of parameters (one variable arbitrary parameter, one must be passed in an array as a parameter set). Here we take call as an example to explain the object impersonation inheritance implemented by call.

function Rect(width, height){
this.width = width;
this.height = height;
this.area = function(){return this.width*this.height;};
}
function myRect(width, height, name){
Rect .call(this,width,height);
this.name = name;
this.show = function(){
alert(this.name+” with area:”+this.area());
}
}

Regarding the Call method, the official explanation: Call a method of an object to replace the current object with another object.

call (thisOb,arg1, arg2…)

This is also a kind of object impersonation inheritance. In fact, what happens when the call method is called is the replacement of the context environment variable this. In the myRect function body, this must point to an instance of the class myRect object. However, use this as the context environment variable to call the method named Rect, which is the constructor of the Rect class.

So when calling Rect at this time, the assignment attributes and methods to this are actually performed on a myRect object. So although call and apply are not new methods just for inheritance, they can be used to simulate inheritance.

This is what objects pretend to be inherited. It can achieve multiple inheritance, as long as you repeat this set of assignment processes. However, it is not really used on a large scale at present. Why?

Because it has an obvious performance defect, this is about the concept of OO. We say that an object is a collection of member methods. When constructing object instances, these instances only need to have their own member variables. Okay, the member method is just an executable text area that operates on variables. This area does not need to be copied for each instance, and all instances can share it.

Now back to JS's inheritance of using objects to pretend to be simulated, all member methods are created for this, that is, all instances will have a copy of the member methods, which is a reference to memory resources. An extreme waste.

Other flaws, such as object impersonation and the inability to inherit variables and methods in the prototype domain, need not be mentioned. I think the previous fatal flaw is enough. However, we still need to understand it, especially the principle of how the properties and methods of the parent class are inherited, which is very important for understanding JS inheritance.

[Recommended learning: javascript advanced tutorial]

(2) Prototype method

The second inheritance method is prototype Method, the so-called prototype method inheritance, refers to the use of prototype or covering the prototype in some way, so as to achieve the purpose of attribute method copying. There are many ways to implement it, and there may be some differences between different frameworks, but if we grasp the principles, there will be nothing we don’t understand. Look at an example (a certain implementation):

function Person(){
this.name = “Mike”;
this.sayGoodbye = function(){alert(“GoodBye!”);};
}
Person.prototype.sayHello = function(){alert(”Hello!”);};
function Student(){}
Student.prototype = new Person();

The key is to assign the value of the Student prototype attribute in the last sentence to the object constructed by the Person class. Here I explain how the attributes and methods of the parent class are copied to the subclass. of.

When a Js object reads the attributes of an object, it always checks the attribute list of its own domain first. If there is one, it returns it. Otherwise, it reads the prototype domain. If it is found, it returns it, because prototype can point to other things. Object, so the JS interpreter will recursively search for the prototype field of the object pointed to by the prototype field, and stop until the prototype is itself. If it is not found at this time, it becomes undefined.

这样看来,最后一句发生的效果就是将父类所有属性和方法连接到子类的prototype域上,这样子类就继承了父类所有的属性和方法,包括name、 sayGoodbye和sayHello。这里与其把最后一句看成一种赋值,不如理解成一种指向关系更好一点。

这种原型继承的缺陷也相当明显,就是继承时 父类的构造函数时不能带参数,因为对子类prototype域的修改是在声明子类对象之后才能进行,用子类构造函数的参数去初始化父类属性是无法实现的, 如下所示:

function Person(name){
this.name = name;
}
function Student(name,id){
this.id = id;
}
Student.prototype = new Person(this.name);

两种继承方式已经讲完了,如果我们理解了两种方式下子类如何把父类的属性和方法“抓取”下来,就可以自由组合各自的利弊,来实现真正合理的Js继承。下面是个人总结的一种综合方式:

function Person(name){
this.name = name;
}
Person.prototype.sayHello = function(){alert(this.name+“say Hello!”);};
function Student(name,id){
Person.call(this,name);
this.id = id;
}
Student.prototype = new Person();
Student.prototype.show = function(){
alert(“Name is:”+ this.name+” and Id is:”+this.id);

总结就是利用对象冒充机制的call方法把父类的属性给抓取下来,而成员方法尽量写进被所有对象实例共享的prototype域中,以防止方法副本重复创 建。然后子类继承父类prototype域来抓取下来所有的方法。

如想彻底理清这些调用链的关系,推荐大家多关注Js中prototype的 constructor和对象的constructor属性,这里就不多说了。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of What are the two forms of javascript inheritance?. For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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