首页 > 编程语言 >[Javascript] Class & Prototypes

[Javascript] Class & Prototypes

时间:2024-03-13 19:24:01浏览次数:32  
标签:Javascript Object Prototypes User constructor new getPrototypeOf Class dog1

Create a new User instance would create a new login function in memory each time?

class User {
  constructor(username) {
     this.username = username;
  }
    
  login() {...}
}
    
const user1 = new User("johndoe");
const user2 = new User("jonedoe");

 

Answer:

查看代码
 false

 

The only thing is added to the instance is usernameprop, the loginmethod will be added to prototype.

 

Which of the following statements are true?

class Dog {
    constructor(name) {
        this.name = name;
        this.wagTail = () => "Wagging tail!"
    }
    bark() {
        return "Woof!
    }
}

const dog1 = new Dog("Max");
const dog2 = new Dog("Spot");
dog1.wagTail() === dog2.wagTail()
dog1.wagTail === dg2.wagTail
dog1.bark === dog2.bark
Object.getPrototypeOf(dog1) === Object.getPrototypeOf(dog2)
dog1.constructor === dog2.constructor

 

Answer:

查看代码
 dog1.wagTail() === dog2.wagTail()                                // true
dog1.wagTail === dg2.wagTail                                     // false
dog1.bark === dog2.bark                                          // true
Object.getPrototypeOf(dog1) === Object.getPrototypeOf(dog2)      // true
dog1.constructor === dog2.constructor                            // true !

constructorare just the same functions for each instance, so it is equal.

It doesn't make sense to add wagTailto the constructor, it should be on the proptotype.

 

Object.create

class Counter {
    constructor(initialCount = 0) {
        this.count = initialCount
    }
    
    increment() { return this.count++ }
}

const counterOne = new Counter(1)
counterOne.increment()
const counterTwo = Object.create(counterOne)
counterTwo.increment()

The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.

const counterTwo = Object.create(counterOne)

At this mement, if you log out  counterTwo, you will find that countis not exist on counterTwoitself, but exists on prototype.

 

Now if you want to modify the property not exist on the object self, it will copy the property from the prototype

counterTwo.increment()

 

 

Static 

class Chameleon {
    constructor(color="green") {
        this.color = color
    }
    static changeColor(newColor) {
        this.color = newColor
        return this.color
    }
}

const freddie = new Chameleon("green")
freddie.changeColor("orange") // TypeError: static properties only exists on Class not on instances

 

Prototype

class User {
    constructor(username) {
        this.username = username;
    }
    login() {...}
}
    
const user = new User("johndoe")

Object.getPrototypeOf(user) === User.prototype; // true
user.prototype === User.protottype; // false
Object.getPrototypeOf(user) === Object.getPrototypeOf(User) // false
Object.getPrototypeOf(user) === User.prototype // false

 

User.prototype // {login: f}
Object.getPrototypeOf(user) // {login: f}
Object.getPrototypeOf(User) // f () { [navtive code] }
user.prototype // undefined

 

标签:Javascript,Object,Prototypes,User,constructor,new,getPrototypeOf,Class,dog1
From: https://www.cnblogs.com/Answer1215/p/18066375

相关文章

  • 【Coursera GenAI with LLM】 Week 2 Fine-tuning LLMs with instruction Class Notes
    GenAIProjectLifecycle:Afterpickingpre-trainedmodels,wecanfine-tune!In-contextlearning(ICL):zero/one/fewshotinference.Includingafewmodelsinthepromptformodeltolearnandgenerateabettercomplement(akaoutput).Itsdrawbacks......
  • 【Javascript】 Promise 对象(一)
    Promise的含义Promise是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6将其写进了语言标准,统一了用法,原生提供了Promise对象。所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操......
  • JavaScript学习--splice()函数入门与精通
    一、splice入门splice方法:通过删除(两个参数)或替换现有元素(三个参数)或者原地添加新的元素(三个参数)来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。参数:index——必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置(从1开始)。howmany——必需......
  • 浅谈JavaScript
    第一章JavaScript学前准备1.JavaScript简介(1)1992年Nombas的scriptease奠定了JavaScript思想理念;(2)受当时网速的限制,很多操作过程很漫长,如用户注册个账号,先提交到服务器去验证合法性,然后再返回给用户。Netscape发现了这个问题并开发了JavaScript语言,同时微软也开发了一个叫J......
  • JavaScript 高阶技巧
    0x01深浅拷贝开发中经常需要拷贝(复制)一个对象,如果直接赋值,则对拷贝对象的修改会影响到源对象consto1={a:1,b:2}consto2=o1console.log(o2)//{a:1,b:2}o2.a=3console.log(o1)//{a:3,b:2}console.log(o2)//{a:3,b:2}原因在于,直......
  • 跨端轻量JavaScript引擎的实现与探索
    一、JavaScript1.JavaScript语言JavaScript是ECMAScript的实现,由ECMA39(欧洲计算机制造商协会39号技术委员会)负责制定ECMAScript标准。ECMAScript发展史:时间版本说明1997年7月ES1.0发布当年7月,ECMA262标准出台1998年6月ES2.0发布该版本修改完全符合ISO......
  • cglib FastClass机制
    前言关于动态代理的一些知识,以及cglib与jdk动态代理的区别,在这一篇已经介绍过,不熟悉的可以先看下。本篇我们来学习一下cglib的FastClass机制,这是cglib与jdk动态代理的一个主要区别,也是一个面试考点。我们知道jdk动态代理是使用InvocationHandler接口,在invoke方法内,可以使用Meth......
  • UVM宏解释+odt文件转doc+merge命令和difflib+python调用命令+clog2和系统函数+java添
    UVM宏解释UVM_DISABLE_AUTO_ITEM_RECORDINGhttps://blog.csdn.net/MGoop/article/details/127295965itemrecord的方法主要是用于记录事务信息的,原理是调用accept_tr,begin_tr,end_tr。似乎和波形上显示出各个事务相关。默认情况下,在调用get_next_item()和item_done()时自动......
  • JavaScript逆向之有道翻译加解密全过程解析
    本篇文章用于解析有道翻译中的加解密全过程url:https://fanyi.youdao.com/index.html#/加密访问网址,输入框中随便输入一个英文单词,查看触发流量包,只看Fetch/XHR类型的。这里主要关注webtranslate的这条,请求参数和响应数据都是有加密的,主要了解其的加解密逻辑。根据url定位......
  • Find class object in a library file
    Youmaygetalinkererrorthatsaysasysbolwasnotfoundduringlinkingstage.Thisisproblelybecausesomelibrarywasnotaddedrightly.Hereisabashscripttofindwhichlibraryisthemissing classsymbolin.!/bin/bashfunctiondoDir(){......