Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement prototype chain and inheritance in JavaScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to achieve prototype chain and inheritance in JavaScript". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to achieve prototype chain and inheritance in JavaScript" can help you solve the problem.

Prototype chain example (the main points are written in comments, you can copy the code to the browser for testing, the same below)

Function foo () {} / / define a function object foo.prototype.z = 3 through function foo () {}; / / the function defaults with a prototype object attribute (typeof foo.prototype;// "object") var obj = new foo (); / / We construct a new object obj.y = 2 through the new foo () constructor / / add two attributes to obj obj.x = 1 by assignment; / / construct the object in this way. The prototype of the object points to the prototype property of the constructor, that is, foo.prototype obj.x; / / 1 / / when accessing obj.x, it is found that there is an x attribute on obj, so 1 obj.y is returned. / / 2 / when accessing obj.y, it is found that there is a y attribute on obj, so return 2 obj.z; / / 3 / / when accessing obj.z, it is found that there is no z attribute on obj, what should I do? It will not stop looking, it will look for its prototype, that is, foo.prototype, and it will find z, so it returns 3 / / the default prototype object of the object or function that we created literally, in fact, it also has a prototype, its prototype points to Object.prototype, and then Object.prototype also has a prototype, its prototype points to null. / / what is the function of the Object.prototype here? Typeof obj.toString; / / 'function' / / We found that typeof obj.toString is a function, but there is no toString method either on the object or on the object prototype, because there is an Object.prototype method before the end of the prototype chain null, and toString is the method above Object.prototype. This also explains why basically all JS objects have the toString method'z' in obj; / / true / / obj.z inherited from foo.prototype, so'z' in obj returns true obj.hasOwnProperty ('z'); / / false / / but obj.hasOwnProperty ('z') returns false, indicating that z is not on the obj direct object, but is a property on the object's prototype chain. (hsaOwnProperty is also a method on Object.prototype)

Just now we visited XQuery y and z, and looked for them through the prototype chain, respectively. We can know that when we visit a property of an object and there is no corresponding property on the object, it will look up through the prototype chain, and it will return undefined if it has not yet found null.

Prototype-based inheritance

Function Foo () {this.y = 2;} Foo.prototype.x = 1; var obj3 = new Foo (); / / ① when called using new, the function will act as a constructor to call ② this will point to an object (in this case, obj3), and the prototype of this object will point to the constructor's prototype property (here Foo.prototype) obj3.y; / / 2 obj3.x / / 1 / / you can see that y is on the object and x is the prototype on the prototype chain (that is, on Foo.prototype)

Prototype attributes and prototypes

Let's take a look at the structure of Foo.prototype. When we use a function declaration to create an empty function, then the function has a prototype property, and it has two properties by default, constructor and _ _ proto__.

The constructor attribute points to itself that Foo,__proto__ is exposed in chrome (not a standard property, just know it), so the prototype of Foo.prototype points to Object.prototype. So on Object.prototype

Some of the methods toString,valueOf will be used by each general object.

Function Foo () {} typeof Foo.prototype; / / "object" Foo.prototype.x = 1; var obj3 = new Foo ()

To sum up: we have a Foo function here, which has an object property of prototype, and its purpose is that when you use new Foo () to construct an instance, the prototype property of this constructor will be used as a prototype for these objects from new.

So let's be clear, prototype and prototype are two different things. Prototype is the default property on the function object, and the prototype is usually the prototype property on the constructor.

Implement one class to inherit another class

If function Person (name, age) {this.name = name; / / is called directly, this points to the global object (this knowledge points) this.age = age / / if you use new to call Peoson, this will point to the empty object whose prototype is Person.prototype, and assign a value to the empty object through this.name * this as a method for creating a share of all Person instances through Person.prototype.hi} Person.prototype.hi = function () (you can refer to the figure on the left of the previous section: the prototype of the object points to the prototype property of the constructor, so if you want obj1,obj2,obj3 to share some methods, you only need to add properties and methods to the prototype object at once) Console.log ('Hi, my name is'+ this.name +', I am'+ this.age + 'years old now.') / / this here is the global object}; Person.prototype.LEGS_NUM = 2; / / set some data shared for all instances of the Person class Person.prototype.ARMS_NUM = 2; Person.prototype.walk = function () {console.log (this.name +' is walking...');} Function Student (name, age, className) {/ / each student belongs to human Person.call (this, name, age); / / call the parent class this.className = className;} / / in the subclass Student first. The next step is how to inherit some methods of Person.prototype Student.prototype = Object.create (Person.prototype) from Student instances. / / Object.create (): create an empty object, and the prototype of the object points to its parameters / / so that we can look up Person.prototype when we visit Student.prototype, or create our own method Student.prototype.constructor = Student without affecting Person / / keep consistency. If not set, constructor will point to Person Student.prototype.hi = function () {/ / override our base class Person.prototype.hi console.log ('Hi, my name is'+ this.name +', I am'+ this.age + 'years old now, and from' + this.className +'.') with an assignment like Student.prototype.hi. } Student.prototype.learn = function (subject) {/ / at the same time, we also have our own learn method console.log (this.name +'is learning'+ subject + 'at' + this.className +'.);}; / / test var yun = new Student ('Yunyun', 22,' Class 3 Magnum 2'); yun.hi (); / / Hi,my name is Yunyun,I'm 22 years old now,and from Class 3 console.log (yun.ARMS_NUM) / / 2 / We do not have our own object, nor does the prototype of the object, namely Student.prototype, but we use inheritance, continue to look up, and find Person.prototype.ARMS_NUM, so we return 2 yun.walk (); / / Yunyun is walking... Yun.learn ('math'); / / Yunyun is learning math at Class 3.

Combined with the figure, let's analyze the above code in reverse: we first create an instance of Student through new Student. The prototype of yun,yun points to the prototype property of the constructor (here is Student.prototype). There are hi and learn methods on Student.prototype, and Student.prototype is constructed through Object.create (Person.prototype), so the Student.prototype here is an empty object. And the prototype of this object points to Person.prototype, and then we also set the LEGS_NUM,ARMS_NUM property and the hi,walk method on Person.prototype. Then we directly define a Person function, Person.prototype is a preset object, it will also have its prototype, its prototype is Object.prototype, and it is precisely because of this that any object has some common functions like hasOwnProperty,valueOf,toString, which are all derived from Object.prototype. In this way, inheritance based on prototype chain is implemented. So what happens when we call the hi,walk,learn method? For example, when we call the hi method, we first look to see if there is a hi method on the object yun, but it does not exist in this instance, so we will look up and find that the prototype of yun, that is, the hi method is on Student.protoype, so the final call is Student.prototype.hi, and other methods are similar.

Change prototype

We know that prototype prototypes in JavaScript are not as difficult to change dynamically as class in class,Java in Java, but prototypes in JavaScript are actually ordinary objects, which means that we can also dynamically add or remove attributes to prototype during the running phase of the program.

Based on the above code, we already have an example of yun, so let's go on to experiment:

Tudent.prototype.x = 101; / / dynamically add an attribute x yun.x; / / 101 / / to the prototype of yun through Student.prototype.x / / then we find that all instances are affected / / then we do an interesting experiment, Student.prototype = {YV2}; / / We directly modify the prototype property of the constructor and assign it to a new object yun.y. / / undefined yun.x; / / 101 / / so we conclude that when we modify the value of Student.prototype, we cannot change the instantiated object var Tom = new Student ('Tom',3,'Class LOL KengB'); Tom.x; / / undefined / / but when we create a new instance, x is gone, Tom.y / / 2 / and y is the new value

So when you dynamically modify prototype, it will affect all the created or newly created instances, but if you change the entire prototype assignment to a new object, it will not affect the created instances, but it will affect subsequent instances.

The way to implement inheritance

There are many ways to implement inheritance, so let's analyze it in terms of Person and Student

Function Person () {

}

Function Student () {

}

Student.prototype = Person.prototype; / / can we use this way? This approach is wrong: because the subclass Student has some of its own methods

/ /, if you assign a value like this, you change the Student as well as the Person.

Student.prototype = new Person (); / / this is possible, but sometimes there are problems in calling the constructor, such as passing in a name and age of Person.

/ /, the Student here is a class and has not yet been instantiated, which is a little strange at this time.

Student.prototype = Object.create (Person.prototype); / / this is relatively ideal, here we create an empty object

/, and the prototype of the object points to Person.prototype, so we make sure that we inherit the methods on Person.prototype and that Student.prototype has its own empty object.

/ / but Object.create is available only after ES5.

This is the end of the introduction to "how JavaScript implements prototype chain and inheritance". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report