【问题标题】:Confusion about when to use prototype in Crockford's example of Pseudoclassical Inheritance关于何时在 Crockford 的伪经典继承示例中使用原型的困惑
【发布时间】:2016-08-10 20:43:10
【问题描述】:

在 Douglas Crockford 的 JavaScript: The Good Parts 中,他用这段代码解释了伪经典继承的概念,其中显示 Cat 继承自 Mammal

var Cat = function (name) {
        this.name = name;
        this.saying = 'meow';
};
    // Replace Cat.prototype with a new instance of Mammal

    Cat.prototype = new Mammal();

    // Augment the new prototype with
    // purr and get_name methods.

    Cat.prototype.purr = function (n) {
        var i, s = '';
        for (i = 0; i < n; i += 1) {
            if (s) {
               s += '-'; 
            }
            s += 'r'; 
         }
         return s; 
    };

    Cat.prototype.get_name = function () { 
        return this.says() + ' ' + this.name +
                ' ' + this.says();
    };

var myCat = new Cat('Henrietta');
var says = myCat.says(); // 'meow'
var purr = myCat.purr(5); // 'r-r-r-r-r' var name = myCat.get_name();
// 'meow Henrietta meow'

然后他介绍了一种称为“继承”的新方法,以帮助使代码更具可读性。

Function.method('inherits', function (Parent) { 
   this.prototype = new Parent();
   return this;
});

他再次展示了使用新的“继承”方法的示例。

var Cat = function (name) {
         this.name = name;
         this.saying = 'meow';
     }.
         inherits(Mammal).
         method('purr', function (n) {
             var i, s = '';
             for (i = 0; i < n; i += 1) {
                 if (s) {
                     s += '-';
        }
        s += 'r'; 
    }
    return s; 
    }).
    method('get_name', function () {
        return this.says() + ' ' + this.name + ' ' + this.says();
});

在我看来,在这个新示例中,purrget_name 是直接在 Cat 对象上定义的,而在第一个示例中它们是在 Cat.prototype 上定义的。是对的吗?如果是这样,他为什么不在Cat.prototype 上定义他的新方法?有区别吗?

【问题讨论】:

  • 呃,你确定他做了Cat.prototype = new Mammal();(没有解释它是怎么错的)?我以为他会更清楚。
  • 在前一章(第 4 章)中,他将受经典启发的语法称为“两全其美”,并说“使用这种风格 [意思是 new 关键字] 的构造函数不是推荐。我们将在下一章看到更好的选择。”
  • 这本书和一些盐一起吃。为了效率,我实际上建议扔掉这本书,只保留盐,它更适用于现代 JS(或者实际上是 Crockford 没有自己编写的任何 JS)。
  • 您会推荐哪些书籍? :)

标签: javascript inheritance prototype


【解决方案1】:

purrget_name 直接在 Cat 对象上定义,而在第一个示例中它们是在 Cat.prototype 上定义的。是对的吗?

没有。虽然他在Cat 函数上调用method 方法,但它确实在接收者的.prototype 属性上定义了方法。不妨翻开几页,再看看Function.prototype.method 的代码:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

有影响吗?

是的,会的。

【讨论】:

  • 我冒昧地为method 方法添加了书中的代码,以使答案更加独立。希望没关系!
  • @MichaelGeary 很好!
猜你喜欢
  • 2015-10-12
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 2011-12-18
  • 2016-04-10
相关资源
最近更新 更多