繁体   English   中英

关于何时在Crockford的Pseudoclassical Inheritance示例中使用原型的困惑

[英]Confusion about when to use prototype in Crockford's example of Pseudoclassical Inheritance

在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'

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

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.prototypeCat.prototype 那正确吗? 如果是这样,为什么他没有在Cat.prototype上定义他的新方法? 这有什么不同吗?

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

不。虽然他在Cat函数上调用method方法,但它确实在接收器的.prototype属性上定义了方法。 也许回头几页,再看一下Function.prototype.method的代码:

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

这有什么不同吗?

是的,它会的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM