gpt4 book ai didi

javascript - 什么时候直接向 JavaScript 中的对象添加属性更好?

转载 作者:行者123 更新时间:2023-12-03 05:19:17 24 4
gpt4 key购买 nike

假设我们正在定义一个 Person 构造函数并创建一个像这样的新人:

function Person(name){
this.name = name;
}
var person = new Person("John Doe");

以下 2 个实现输出:Hello from John Doe:

第一次实现

person.sayHello = function(){console.log("Hello from " + this.name);}

运行代码1

function Person(name){this.name = name;}
var person = new Person("John Doe");
person.sayHello = function(){console.log("Hello from " + this.name);}
person.sayHello();

第二次实现

Person.prototype.sayHello = function(){console.log("Hello from " + this.name);}

运行代码2

function Person(name){this.name = name;}
var person = new Person("John Doe");
Person.prototype.sayHello = function(){console.log("Hello from " + this.name);}
person.sayHello();

我的问题是:

  1. 由于结果相似,什么时候直接将属性添加到创建的对象中更好?

最佳答案

简单来说,使用对象的原型(prototype)用于在创建对象后扩展对象属性。最好的用例之一是,当类不是由您编写或从某个地方导入时,您需要扩展它。

Are the 2 implementations similar (I'm not talking about the result but for side effects)?

据我所知,是一样的。

If no, what are the differences and when we should choose the first one or the second one?

是的,但是何时使用,请参见上文。

关于javascript - 什么时候直接向 JavaScript 中的对象添加属性更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465991/

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