What are the two forms of javascript inheritance?

青灯夜游
Release: 2023-01-04 09:35:08
Original
1638 people have browsed it

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)}; }
Copy after login

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()); } }
Copy after login

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…)
Copy after login

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();
Copy after login

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);
Copy after login

两种继承方式已经讲完了,如果我们理解了两种方式下子类如何把父类的属性和方法“抓取”下来,就可以自由组合各自的利弊,来实现真正合理的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);
Copy after login

总结就是利用对象冒充机制的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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!