首页 > 编程语言 >[Javascript] Prototype Pattern

[Javascript] Prototype Pattern

时间:2022-08-26 18:24:55浏览次数:87  
标签:console name Pattern age Javascript properties Prototype class log

Source: https://javascriptpatterns.vercel.app/patterns/design-patterns/prototype-pattern

 

If you use factory pattern to create object:

const createDog = (name, age) => ({
  name,
  age,
  bark() {
    console.log(`${name} is barking!`);
  },
  wagTail() {
    console.log(`${name} is wagging their tail!`);
  },
});

In memroy, it looks like this:

If you use Class:

class Dog {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  bark() {
    console.log(`${this.name} is barking!`);
  }
  wagTail() {
    console.log(`${this.name} is wagging their tail!`);
  }
}

 In memory, it looks like this:

Memory efficient: The prototype chain allows us to access properties that aren't directly defined on the object itself, we can avoid duplication of methods and properties, thus reducing the amount of memory used.

Readaibility: When a class has been extended many times, it can be difficult to know where certain properties come from.

For example, if we have a BorderCollie class that extends all the way to the Animal class, it can be difficult to trace back where certain properties came from.

One

 

Under __proto__ and .prototype.

标签:console,name,Pattern,age,Javascript,properties,Prototype,class,log
From: https://www.cnblogs.com/Answer1215/p/16628546.html

相关文章

  • [Javascript] Factory pattern vs Class instance
    InJavaScript,thefactorypatternisn'tmuchmorethanafunctionthatreturnsanobjectwithoutusingthe new keyword. ES6arrowfunctions allowustocr......
  • JavaScript变量及声明
    本文介绍了如何使用语法和示例声明和使用变量。变量用于将数据存储在JavaScript代码中。在JavaScript中使用变量之前,必须先对其进行声明。让我们看一下如何声明一个变量。......
  • JavaScript if else语句
    在编写程序时,可能需要从一组给定的路径中采用一个。在这种情况下,您需要使用条件语句,以使程序可以做出正确的决定并执行正确的操作。在JavaScript中,if-else语句用于在条件......
  • JavaScript switch语句
    除了if...else之外,JavaScript还有一个称为switch语句的功能。switch是一种条件语句,它将针对多种可能的情况评估表达式,并根据匹配的情况执行一个或多个代码块。switch语......
  • [Javascript] Singleton Pattern
    Source:https://javascriptpatterns.vercel.app/patterns/design-patterns/singleton-patternWiththeSingletonPattern,werestricttheinstantiationofcertainc......
  • JavaScript基础回顾知识点记录7-事件补充说明2
    js中鼠标滚轮事件offsetWidth/offsetHeight-对象的可见宽度/高度clientWidth/clientHeight-内容的可见宽度/高度scrollWidth/scrollHeight......
  • JavaScript快速入门-06-函数
    6函数6.1函数定义  函数可以封装语句,然后在任何地方、任何时间执行。JavaScript中的函数使用function关键字声明,主要由函数名、函数参数和函数体组成。其基本语法......
  • 2022-8-25第一组孙乃宇JavaScript
    JavaScript最后元素的属性获取元素的属性所有的HTML元素,我们可以根据具体需求,自定义添加属性<divhaha="abc"id="xyz"name="123"></div>获取这个属性的值为什么na......
  • JavaScript知识-函数基础知识、匿名函数、闭包函数、箭头函数、js内置对象和方法
    目录JavaScript函数1.函数的语法格式2.无参函数3.有参函数4.关键字arguments5.函数返回值关键字return6.匿名函数(没有函数名)7.箭头函数8.函数的全局变量与局部变量9.闭包......
  • JavaScript中改变鼠标指针样式的方法
    JavaScript中改变鼠标指针样式的方法    在js中我们可以通过style对象的cursor属性来设置鼠标指针的样式,例varbody=document.querySelector("body") body.style......