gpt4 book ai didi

javascript - 在原型(prototype)中添加函数与在 OOP Javascript 中将其声明为变量

转载 作者:行者123 更新时间:2023-11-30 14:39:38 25 4
gpt4 key购买 nike

将函数添加到原型(prototype)对象与简单地在构造函数的变量上声明它有什么优势或不同?

这是一样的,这就是我们所说的Person

const James = new Person('James')
James.greet()

向原型(prototype)对象添加问候语

const Person = name => {
this.name = name
}
Person.protoype.greet = () => console.log(`my name is ${this.name}!`)

将问候添加到构造函数

const Person = name => {
this.name = name
this.greet = () => console.log(`my name is ${this.name}!`)
}

当我们多次调用 Person 时,在构造函数中添加 greet 是否会复制函数?我知道对象方法的缺点有这个问题,例如

const Person = () => ({
name: '',
greet: () => console.log(`my name is ${this.name}!`)
})
const James = Person('James') //greet copy 1
James.greet()
const Alice = Person('Alice') //greet copy 2
Alice.greet()

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com