In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to achieve prototype and prototype chain in Javascript", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve prototype and prototype chain in Javascript" article.
Prototype
There is a saying in Javascript that everything is an object, of course, this sentence is not strict, for example, null and undefined are not objects, except for these two, it can be said that everything in Javascript is an object. Javascript objects all have a public property called prototype, whose name is _ proto_. This prototype property is a reference to another object, through which we can access all the properties and methods of another object. For example:
Let numArray = [1,2,-8, 3,-4, 7]
The Array object has a prototype property that points to Array.prototype, and the variable numArray inherits all the properties and methods of the Array.prototype object.
This is why methods like sort () can be called directly:
Console.log (numArray.sort ()) / /-> [- 4,-8, 1, 2, 3, 7]
In other words:
NumArray.__proto__ = Array.prototype / / true
The same is true for other objects (functions) (such as Date (), Function (), String (), Number (), etc.)
When a constructor is created, the instance object inherits the prototype properties of the constructor, which is a very important feature of the constructor. Use the new keyword in Javascript to instantiate the constructor. Look at the following example:
Const Car = function (color, model, dateManufactured) {this.color = color; this.model = model; this.dateManufactured = dateManufactured;}; Car.prototype.getColor = function () {return this.color;}; Car.prototype.getModel = function () {return this.model;} Car.prototype.carDate = function () {return `This ${this.model} was manufactured in the year ${this.dateManufactured} `} let firstCar = new Car ('red',' Ferrari', '1985'); console.log (firstCar); console.log (firstCar.carDate ())
In the above example, the method getColor,carDate,getModel is the method of the object (function) Car, while the instance object firstCar of Car can inherit all the methods and properties on the Car prototype.
Conclusion: each instance object has a private property, _ proto_, that points to its constructor prototype object (prototype).
Prototype chain
In Javascript, if you access a property or method that does not exist in the object itself, first look for it on its prototype object, and if it does not exist on the prototype object, continue to look for it on the prototype object until it is found. So does the prototype object have an end? The prototype of all objects ends with Object.prototype, so what does the _ proto_ of the Object.prototype object point to? The answer is null. The _ proto_ of most of the objects we use in our daily development basically don't point directly to Object.prototype, but basically point to another object. For example, the _ proto_ of all functions points to Function.prototype, and the _ proto_ of all arrays points to Array.prototype.
Let protoRabbit = {color: 'grey', speak (line) {console.log (`The ${this.type} rabbit says ${line} `);}}; let killerRabbit = Object.create (protoRabbit); killerRabbit.type = "assassin"; killerRabbit.speak ("SKREEEE!")
In the above code, the variable protoRabbit is set to the set of public property objects of all rabbit objects. The rabbit killerRabbit inherits all the properties and methods of protoRabbit through the Object.create method, and then assigns a type attribute to killerRabbit. See the following code:
Let mainObject = {bar: 2}; / / create an object linked to `anotherObject` let myObject = Object.create (mainObject); for (let k in myObject) {console.log ("found:" + k);} / / found: bar ("bar" in myObject)
For example, the variable myObject itself does not have a bar attribute, but here it will follow the prototype chain layer by layer until it is found or the prototype chain ends. If the property is not found at the end of the prototype chain, undefined will be returned when accessing the property.
The process of iterating over an object using the for...in keyword is similar to accessing a property above and following the prototype chain, traversing all the attributes on the prototype chain (regardless of whether the attributes can be enumerated or not).
Let protoRabbit = {color: 'grey', speak (line) {console.log (`The ${this.type} rabbit says ${line} `);}}; let killerRabbit = Object.create (protoRabbit); killerRabbit.type = "assassin"; killerRabbit.speak ("SKREEEE!")
Accessing speak in the above code is very efficient, but if we want to create many Rabbit objects, we have to rewrite a lot of code. And this is the opportunity for prototypes and constructors to really display their talents.
Let protoRabbit = function (color, word, type) {this.color = color; this.word = word; this.type = type;}; protoRabbit.prototype.getColor = function () {return this.color;} protoRabbit.prototype.speak = function () {console.log (`The ${this.type} rabbit says ${this.word} `);} let killerRabbit = new protoRabbit ('grey',' SKREEE, 'assassin'); killerRabbit.speak ()
As in the code above, you can save a lot of code by using the constructor.
Conclusion: each instance object has a private property, _ proto_, that points to its constructor prototype object (prototype). The prototype object also has its own _ proto_, up until the prototype object of an object is null. This layer of prototype is the prototype chain.
Four ways to create an object
Literal object
This is one of the more common ways:
Let obj = {}
Constructor creation
Constructors are created more often to implement inheritance, polymorphism, encapsulation and other features in Javascript.
Function Animal (name) {this.name = name;} let cat = new Animal ('Tom')
Class creation
The class keyword is a new feature introduced by ES6, which is actually a syntactic sugar implemented based on prototypes and prototype chains.
Class Animal {constructor (name) {this.name = name;}} let cat = new Animal ('Tom')
Four methods of extending prototype chain
Constructor creation
The above example is useful to the example of creating an object using a constructor. Let's look at a practical example:
Function Animal (name) {this.name = name;} Animal.prototype = {run () {console.log ('running');}} let cat = new Animal ('Tom'); cat.__proto__ = Animal.prototype; / / true Animal.prototype.__proto__ = Object.prototype; / / true
Pros: support for current and all imaginable browsers (IE5.5 can be used). This approach is very fast, very standard-compliant, and takes full advantage of JIST optimization.
Cons: in order to use this method, the functions in this problem must be initialized. In addition, the initialization of the constructor may bring unwanted methods and properties to the generated object.
Object.create
A new method has been introduced in ECMAScript 5: Object.create (). You can call this method to create a new object. The prototype of the new object is the first parameter passed in when the create method is called:
Var a = {a: 1}; / / a-- > Object.prototype-- > null var b = Object.create (a); B. protoprotoplast = = a; / / true
Advantages: support all current browsers that are not Microsoft or above IE9. Allows you to set the _ _ proto__ property directly at once so that the browser can better optimize the object. It also allows you to create an object without a prototype through Object.create (null).
Cons: versions below IE8 are not supported; this slow object initialization can become a performance black hole when using the second parameter, because each object's descriptor property has its own description object. When hundreds of object descriptions are processed in object format, it can cause serious performance problems.
Object.setPrototypeOf
Syntax:
Object.setPrototypeOf (obj, prototype)
Parameters:
The parameter name means the object whose prototype obj wants to set. Prototype the new prototype of the object (an object or null). Var a = {n: 1}; var b = {m: 2}; Object.setPrototypeOf (a, b); a.protoprotoplast = = b; / / true
Advantages: support all modern browsers and Microsoft IE9+ browsers. Allows you to dynamically manipulate prototypes of objects and even force the addition of a prototype to objects without prototypes created through Object.create (null).
Disadvantages: this approach does not perform well and should be discarded; dynamic prototyping interferes with browser optimization of prototypes; browser versions of IE8 and below are not supported.
_ proto_
Var a = {n: 1}; var b = {m: 2}; a. Eggs protoplast = b; a. Eggs protozoa _ = = b; / / true
You can also prototype objects dynamically with _ proto_.
Advantages: support all modern non-Microsoft versions as well as browsers above IE11. Setting _ _ proto__ to a non-object value silently fails and no error is thrown.
Disadvantages: it should be completely discarded because this behavior has no performance at all; interferes with the browser's optimization of prototypes; and does not support browser versions of IE10 or below.
The above is the content of this article on "how to implement prototype and prototype chain in Javascript". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.