哪个更好的 Javascript 对象模式 [英] Which is better Javascript object pattern

查看:50
本文介绍了哪个更好的 Javascript 对象模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个是更好的 Javascript 对象模式...

Which is a better Javascript object pattern ...

function dog(name) {
  this.name = name;
  this.getName = function() {
    return this.name;
  };
};

function cat(name) {
  this.name = name;
};
cat.prototype.getName = function() {
  return this.name;
};

为什么?

----- 编辑

其中一个使用更多内存吗?

Does one or the other use more memory?

一个CPU"密集程度比另一个多还是少?

Is one more or less "CPU" intensive than the other?

哪个更易于维护?

哪个更具可扩展性?

哪个更易读?

推荐答案

除了首选项之外,第二个示例是正确"的示例.在第一个中,您为每个对象创建一个新的 getName 函数.2、所有用这个构造函数创建的对象都会共享prototype/getName.在一个地方改变它,它会随着每个实例而改变.

Preferences aside, the second example is the "right" one. In the first one, you're creating a new getName function for every object. In 2, all objects created with this constructor will share the prototype/getName. Change it in one place and it will change for every instance.

在特殊情况下(如复杂的继承链),您可能需要使用第一个,但要注意它的缺点.

On special occasions (like complex inheritance chains) you might need to use the first, but be aware of it's drawbacks.

这篇博文可能会帮助您更好地理解原型继承.

This blog post might help you understand prototypal inheritance better.

这篇关于哪个更好的 Javascript 对象模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆