javascript - Prototype vs. Not,有什么好处?

标签 javascript prototype

这里我做了两个对象;一个在构造函数中创建访问器方法,另一个在原型(prototype)中创建。为什么人们会选择其中之一而不是另一个?

function spy1(name){
  this.name = name;
  var secret;
  this.setSecret = function(message){
    secret = message;
  };
  this.getSecret = function(){
   return secret;
  };
}

function spy2(name){
  this.name = name;
  this.secret;
  /* (see comment) was:
  var secret;
  */
}
spy2.prototype.setSecret = function(message){
  this.secret = message;
  /*was:
  secret = message;
  */
};
spy2.prototype.getSecret = function(){
  return this.secret;

  /*was:
  return secret;
  */
};

bond = new spy1("007");
smart = new spy2("86");

bond.setSecret("CONTROL is a joke.");
smart.setSecret("The British Secret Service is for sissies.");

最佳答案

主要区别在于,在您的第一个示例中,没有原型(prototype),getSecretsetSecret 函数实现将驻留在 spy1 的每个实例上.

在你的第二个例子中,函数定义在原型(prototype)上,所有实例都直接引用它们,你可以测试它:

var bond = new spy1("007"),
    bond2 = new spy1("007");

bond.getSecret === bond2.getSecret; // <-- false since they are two functions

var smart = new spy2("86"),
    smart2 = new spy2("86");


smart.getSecret === smart2.getSecret; // <-- true since is the same function
                                      // on all instances

另请注意@T.J.评论说,在你的第二个例子中,使用原型(prototype),你无权访问构造函数闭包,为此你正在创建一个 window.secret 全局变量。

如果您打算使用 privileged methods ,扩展原型(prototype)不是一个选项,所有需要访问在构造函数范围内定义的变量的方法都需要在其中声明...

另请参阅:Closures .

关于javascript - Prototype vs. Not,有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1319325/

相关文章:

javascript - jquery datepicker突出显示两个日期之间的事件日期

javascript - 组件函数运行多次react

javascript - 什么是 JavaScript 中的 Empty 函数,为什么它未定义?

javascript - 为什么我不能在函数内设置 JavaScript 原型(prototype)?

javascript - Node.js 可以排队多少个事件?

javascript - 如何将水平滚动条添加到 jquery.bootgrid

javascript - 将原型(prototype)与 "Namespace"用于现有对象

javascript - 字符串无法读取未定义的属性 'replace'

javascript - 是否可以暂时卡住 HTML 元素的当前外观?

JavaScript,原型(prototype)链顶端为null,如何通过代码证明?