gpt4 book ai didi

javascript - 在 JavaScript 中使用原型(prototype)在现实世界中有什么优势吗?

转载 作者:行者123 更新时间:2023-11-29 22:39:47 25 4
gpt4 key购买 nike

我刚读完 Doug Crockford 的 The Good Parts ,他提供了三种不同的继承方式:emulation经典模型、基于原型(prototype)的继承和功能继承。

在后者中,他创建了一个函数,一个工厂,它吐出对象,这些对象使用构建在其他对象上的所需方法进行扩充;类似的东西:

var dog = function(params) {
// animal is the 'super class' created
// the same way as the dog, and defines some
// common methods
var that = animal(params);
that.sound = 'bark';
that.name = function () {};
return that;
}

由于以这种方式创建的所有对象都将引用相同的函数,因此内存占用将比使用 new 运算符时使用的要低得多,例如。问题是,原型(prototype)方法在这种情况下会提供任何优势吗?换句话说,对象原型(prototype)是否以某种方式“更接近金属”以提供性能优势,或者它们只是一种便利机制?

编辑:我将简化问题。原型(prototype)与通过对象组合进行的仿真。只要您不要求所有对象实例都使用新方法进行更新(这是只有原型(prototype)才能提供的便利),那么首先使用原型(prototype)有什么优势吗?

我给 Doug Crockford 发了邮件,他有话要说:

[Using the functional approach above vs. prototypes] isn't that much memory. If you have a huge number of objects times a huge number of methods, then you might want to go prototypal. But memories are abundant these days, and only an extreme application is going to notice it.

Prototypes can use less memory, but can have slightly slower retrieval, particularly if the chains are very long. But generally, this is not noticeable.

最佳答案

实例都引用相同的函数等。每次调用“dog”都会创建一个新的“name”函数实例。

关于javascript - 在 JavaScript 中使用原型(prototype)在现实世界中有什么优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3593012/

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