所以,假设我有以下构造函数,我已经修改了它的原型:
function foo(options) {
this.propA_ = 'whatever';
this.propB_ = 'something';
this.propC_ = options.stuff;
this.randomMethod = function omg() {
/*code etc etc etc*/
}
}
foo.prototype.p1 = 1;
foo.prototype.p2 = 2;
在我制作了 foo 之后,我想创建一个新的构造函数 bar(),它就像一个超级 foo:它具有 foo 的所有属性、原型信息和方法,但它还具有一些额外的属性和方法洒在上面。下面的代码会是最优雅的方式吗?
function foo(options) {
this.propA_ = 'whatever';
this.propB_ = 'something';
this.propC_ = options.stuff;
this.randomMethod = function omg() {
/*code etc etc etc*/
}
}
foo.prototype.p1 = 1;
foo.prototype.p2 = 2;
function bar(options) {
this = foo(options);
this.propD_ = 'yet another thing';
this.propE_ = options.moreStuff;
}
bar.prototype.p3 = 3;
foo.prototype.testing = 'A test';
smallObj = foo()'
bigObj = bar();
运行该代码后,这是我期望得到的
console.log(a.p3); //3
bigObj.p2 = 100;
console.log(bigObj.p2); //100
console.log(foo.prototype.p2); //2
console.log(bigObj.randomMethod()); //Will work
console.log(smallObj.p3); //undefined
console.log(smallObj.propA_); //'whatever'
console.log(bigObj.propA_); //'whatever'
foo.prototype.propA_ = 'something totally different'
console.log(bigObj.propA_); //'something totally different'
这是“扩展”某些现有构造函数的功能以制作一种“Foo Plus”的正确方法吗?基本上,我希望 foo 继续像 bar() 出现之前一样继续工作,但是 bar 是添加在 foo 之上的一组属性和方法。我这样做对吗?