原型与非原型有什么好处? [英] Prototype vs. Not, what are benefits?

查看:43
本文介绍了原型与非原型有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做了两个物体;一个在构造函数中创建了访问器方法,另一个在原型中创建了访问器方法.为什么一个人选择另一个?

Here I made two objects; one has accessor methods created in the constructor, the other in the prototype. Why would one choose one of these over the other?

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.");

推荐答案

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

The primordial differrence is that in your first example, without prototype, the getSecret and setSecret function implementation will reside on every instance of spy1.

在第二个示例中,函数是在原型上定义的,并且所有实例都直接引用了它们,您可以对其进行测试:

On your second example, the functions are defined on the prototype, and all instances refer to them directly, you can test it:

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.在第二个示例中评论说,使用原型,您无权访问构造函数关闭,为此,您正在创建一个 window.secret 全局变量.

Also note what @T.J. commented, in your second example, using the prototype, you don't have access to the constructor function closure, and for that you are making a window.secret global variable.

如果您打算使用特权方法,则不能扩展原型,所有需要访问在构造函数范围内定义的变量的方法都必须在其内部声明...

If you intend to work with privileged methods, extending the prototype is not an option, all the methods that need access to the variables defined within the scope of the constructor function need to be declared inside of it...

另请参见:关闭.

这篇关于原型与非原型有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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