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

What is the prototype pattern in Javascript?

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces what the prototype pattern in Javascript is like, the content is very detailed, interested friends can refer to, hope to be helpful to you.

1. Prototype mode

The prototype pattern is used to improve performance, reduce memory consumption and code reuse by sharing the properties and methods of an object prototype when creating an object.

Example one: function Person (name) {this.name = name; this.config = {a: "1", b: "2",}; this.hello = function () {console.info ("hello");};}

If you need to create 100 instances with the above code, you will need to create 100 config and 100 hello, and the two things are exactly the same in each instance.

So we can optimize the oil by extracting the common code.

Const config = {a: "1", b: "2",}; const hello = function () {console.info ("hello");}; function Person (name) {this.name = name; this.config = config; this.hello = hello}

In this way, no matter how many Person objects are created, only one config and one hello need to be created. However, there are still some problems, such as global variables, mismodification of config, large coupling between Person and other code, difficult code extension and maintenance, and so on.

Therefore, it can be optimized in the way of prototype.

Function Person () {} var p = new Person ()

The prototype image of this function when creating an instance is as follows:

Example 2 function Person (name) {this.name = name; this.config = {a: "1", b: "2",}; this.hello = function () {console.info ("hello");};} / / this way rewrites prototype, causing constructor to be lost and become Object (). / / you can write in Person.prototype.xx=yy, or re-specify Person.prototype.constructor=PersonPerson.prototype = {version: 1.0, say: function (arg) {console.info (`${this.name} say ${arg}`);}, constructor: Person,}; var p1 = new Person ("p1"); var p2 = new Person ("p2"); console.info (p1.config = = p2.config); / / falseconsole.info (p1.hello = p2.hello) / / falseconsole.info (p1.say = = p2.say); / / truep1.say ("qq"); p2.say ("qq"); console.info (p1.version = p2.version); / / trueconsole.info (p1.version)

The prototype image of this function when creating an instance is as follows:

Example 3: function Person (name) {this.name = name; this.config = {a: "1", b: "2",}; this.hello = function () {console.info ("hello");};}; / / this method rewrites prototype, causing constructor to be lost to Object () Person.prototype = {version: 1.0, say: function (arg) {console.info (`${this.name} say ${arg}`) },}; function PersonA (name) {Person.call (this, name);} PersonA.prototype = Person.prototype;function PersonB (name) {Person.call (this, name);} PersonB.prototype = Person.prototype;var pA = new PersonA ("pa"); var pB = new PersonB ("pb"); console.info (pA.config = = pB.config); / / false internal attribute comparison console.info (pA.hello = = pB.hello) / / false internal property comparison console.info (pA.say = pB.say); / / true prototype method sharing pA.say ("qq"); pB.say ("qq"); console.info (pA.version = pB.version); / / true prototype property sharing console.info (pA.version); / / 1.0Person.prototype.version = 2.0; / / modify prototype sharing property console.info (pB.version) / / 2.0console.info (new Person () .version); / / 2.0 pB.say / modify prototype sharing method PersonB.prototype.say = function (arg) {console.info (`v2washi-${this.name} say ${arg} `);}; pB.say ("qq"); new Person ("Person"). Say ("ww")

Summary:

Js consumes more memory and takes a long time to create objects, so it can reduce the memory footprint by reducing the creation of internal properties.

The prototype pattern is to use the prototype features of javascript language to share the same attributes, so as to reduce the memory footprint and improve the efficiency of object creation.

2. Observer mode

The Observer pattern is used for communication between modules and components, and provides a unified pattern for event subscription and event publishing. In order to achieve decoupling between modules and components, and improve the maintainability of the code.

Mode of communication between modules and components

Direct reference communication is adopted between modules and components.

Const moduleA = {say: function (msg) {console.info ("Asay" + msg);}, letBrun: function () {/ / directly references moduleB moduleB.run ();},},}; const moduleB = {run: function () {console.info ("Brun");}, letAsay: function () {/ / directly references moduleA moduleA.say ("hello");},},}; moduleA.letBrun () / / B RunmoduleB.letAsay (); / / Asay hello

The communication mode of parent component is adopted between modules and components.

Const moduleA = {say: function (msg) {console.info ("Asay" + msg);},}; const moduleB = {run: function () {console.info ("Brun");},}; const parentModule = {moduleA, moduleB, letBrun: function () {this.moduleB.run ();}, letAsay: function () {this.moduleA.say ("hello");},},}; parentModule.letBrun () / / B RunparentModule.letAsay (); / / Asay hello

Event module realizes communication

Function Emitter () {this.events = {} This.res_oldAction = {} this.res_action_events = {}} / / subscription resources Emitter.prototype.subscribe = function (res, action, fn) {if (! this.res_ oldAction [res.name]) {this.res_ oldAction [res.name] = res [action] res [action] = (data) = > {this.res_ oldAction [res.name] (data) const fns = this.res_action_ eventsres.name] .action; for (let I = 0; I)

< fns.length; i++) { fns[i](data); } } } if(!this.res_action_events[res.name]){ this.res_action_events[res.name] = {} } if(!this.res_action_events[res.name][action]){ this.res_action_events[res.name][action] = [] } this.res_action_events[res.name].action.push(fn)}//取消订阅资源Emitter.prototype.unsubscribe = function (res, action, fn) { const fns = this.res_action_events[res.name].action; for (let i = 0; i < fns.length; i++) { if (fns[i] === fn) { fns.splice(i, 1); i--; } }}Emitter.prototype.on = function (name, fn) { if (!this.events[name]) { this.events[name] = []; } this.events[name].push(fn);};Emitter.prototype.remove = function (name, fn) { if (!this.events[name]) { return; } const fns = this.events[name]; for (let i = 0; i < fns.length; i++) { if (fns[i] === fn) { fns.splice(i, 1); i--; } }};Emitter.prototype.fire = function (name, data) { if (!this.events[name]) { return; } const fns = this.events[name]; for (let i = 0; i < fns.length; i++) { fns[i](data); }};const emitter = new Emitter();//模块A中注册事件const methodA = (data) =>

{console.info ("module A receives food message:"); console.info (data);}; emitter.on ("food", methodA); / / event registered in module B const methodB = (data) = > {console.info ("module B receives food message:"); console.info (data);}; emitter.on ("food", methodB); / / trigger event emitter.fire in module C ("food", "here comes") / / remove event emitter.remove ("food", methodB) in module B; / / trigger event emitter.fire again in module C ("food", "here we go again")

The implementation results are as follows:

Module A received a food message:

Here comes the meal.

Module B received a food message:

Here comes the meal.

Module A received a food message:

Here we go again.

The communication mode of js component module is generally divided into three kinds (direct communication, communication through parent component, communication through event module). The observer pattern is used for communication between modules and components, and provides a unified pattern for event subscription and event publishing, so as to achieve decoupling between modules and components and improve the maintainability of the code.

About how the prototype pattern in Javascript is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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: 218

*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

Development

Wechat

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

12
Report