【发布时间】: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();
});
在我看来,在这个新示例中,purr 和 get_name 是直接在 Cat 对象上定义的,而在第一个示例中它们是在 Cat.prototype 上定义的。是对的吗?如果是这样,他为什么不在Cat.prototype 上定义他的新方法?有区别吗?
【问题讨论】:
-
呃,你确定他做了
Cat.prototype = new Mammal();(没有解释它是怎么错的)?我以为他会更清楚。 -
在前一章(第 4 章)中,他将受经典启发的语法称为“两全其美”,并说“使用这种风格 [意思是
new关键字] 的构造函数不是推荐。我们将在下一章看到更好的选择。” -
这本书和一些盐一起吃。为了效率,我实际上建议扔掉这本书,只保留盐,它更适用于现代 JS(或者实际上是 Crockford 没有自己编写的任何 JS)。
-
您会推荐哪些书籍? :)
标签: javascript inheritance prototype