【问题标题】:What's the difference between javascript methods assigned to properties of "this" vs. methods defined on the prototype?分配给“this”属性的javascript方法与原型上定义的方法有什么区别?
【发布时间】:2011-03-24 14:28:44
【问题描述】:

我了解在构造函数中分配为“this”属性的方法的目的是使它们具有特权,因为它们可以访问私有属性和方法,如下所示:

var Book = function(newFirst, newLast){

  //private attributes
  var author_first = newFirst;
  var author_last = newLast;

  //public attributes
  this.puAuthor_first = newFirst;
  this.puAuthor_last = newLast;

  //public privileged methods (accessing private attributes)
  this.getAuthor = function()  {
    return author_first + author_last;
  }

}

但是从 Book 继承的对象与分配给原型对象的方法相比有什么区别:

Book.prototype.nonPrivilegedGetAuthor = function() {
   return this.puAuthor_first + this.puAuthor_last;
} 

?

所以我的问题有两个:

1) 当这个对象通过原型继承继承时,getAuthor() 和 nonPrivilegedGetAuthor() 都会被继承,对吧?这个想法是 getAuthor() 将被复制到新对象,而 nonPrivilegedGetAuthor() 将通过原型链获得,好处是不被复制,对吧?除了无法访问私人会员之外,还有哪些成本?

2) 古典继承呢?具体来说,分配为原型对象属性的公共非特权方法会被继承吗?我应该注意什么?在继承时不做更多的事情,你基本上会在原型链中出现一个跳过一个对象的间隙,对吗?我们必须将子对象的原型链连接到 Book——我们如何做到这一点?我们该怎么做才能正确继承,如果不这样做会发生什么陷阱?

【问题讨论】:

  • 1) Javascript 中没有继承之类的东西 2) Javascript 中没有 public 和 private 之类的东西 3) nonPrivilegedGetAuthor 将有权访问对象属性,因为它是您需要的对象的方法阅读原型,但它基本上是一个用于解析方法范围的对象链。 getAuthor 和 nonPrivilegedGetAuthor 在范围方面几乎没有区别。
  • 我想我得问一个更简单的问题,因为我没有答案可以接受。我会做你的建议。

标签: javascript inheritance prototype


【解决方案1】:

当向一个类的原型添加一个函数(这个词被轻描淡写)时,该类的所有实例都将使用相同的函数。另一方面,如果您使用 this 关键字定义函数,您将只为该实例定义。原型的好处是您可以拥有一个适用于类的所有实例的函数,而不是每次都定义一个新函数。

就继承而言,我必须听从 Douglas Crockford:http://www.crockford.com/javascript/inheritance.html。至于将变量设为私有,没有办法以跨浏览器的方式真正将变量设为私有,但您可以伪造它。我已经用 jPaq 的 Color 对象完成了它,其他人也写过它。再一次,我建议看一下 Douglas Crockford 所说的话:http://www.crockford.com/javascript/private.html。虽然我的方法有点不同,但如果你想让成员私有,这在 JavaScript 中并非不可能。以下是如何以跨浏览器方式实现私有变量的示例:

var Book = (function() {
  var key = {};

  var Book = function(newFirst, newLast) {
    // Private variables stored in an object literal.
    var $ = {
      author_first : newFirst,
      author_last : newLast
    };

    // Public privileged method for accessing private variables.
    this._ = function(aKey) {
      if(aKey === key)
        return $;
      throw new Error("The _() function must be called internally.");
    };
  };

  // Public accessor method.
  Book.prototype.getAuthor = function() {
    var $ = this._(key);
    return $.author_first + " " + $.author_last;
  };

  return Book;
})();

var bookA = new Book("Chris", "West"),
    bookB = new Book("Douglas", "Crockford");
alert(bookA.getAuthor());
alert(bookB.getAuthor());

这与我在 jPaq 中实现私有成员的方式相同。

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2016-06-16
    • 2010-11-20
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多