【问题标题】:javascript .prototype for object function extensions用于对象功能扩展的 javascript .prototype
【发布时间】:2014-06-05 18:50:24
【问题描述】:

--
你好, 希望对 .prototype 的问题有一些小的指导。

我已经浏览了 SO 中的所有答案,但他们似乎没有涵盖这个特定问题,或者他们可能涵盖了,但我没有那样理解。

手头的问题(和代码)

function foo(){};
foo.prototype.type = 'foo';
function bar()
{
    this.prototype = foo.prototype;
}
test = new bar();
console.log(test.type); // type is undefined

问题
据我了解,对type 的请求必须向上级联原型链,直到找到foo 原型,这并没有发生,显然我理解错了 - 为什么类型未定义?

我基本上是想找到一种方法来扩展函数对象,以便

new foo() - 返回一个 foo 对象
new bar() - 返回一个包含 foo 的所有方法和属性的 bar 对象。

感谢我能获得的任何帮助或参考!

【问题讨论】:

标签: javascript


【解决方案1】:

好吧,当你这样做时:

function bar()
{
    this.prototype = foo.prototype;
}

您没有更改 bar 对象原型,而是将一个名为 prototype 的新属性分配给 bar 对象,该对象具有 foo 对象原型,基本上是:{ type: 'foo' }

然后:

test = new bar();
console.log(test.type); // type is undefined

当然是未定义的!你从不定义它,你只定义 prototype 属性

console.log(test.prototype); // I have surprises for you

我想你想要一些像继承这样的想法。我建议使用 Crockford 的继承方式:

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

然后,做:

bar.inherits(foo);

现在,

test = new bar();
console.log(test.type); // foo!

希望对你有帮助

【讨论】:

  • 这不是 Crockford 的继承方式,这是错误的。
  • 嗯,我的立场得到纠正,并收回我声明的第一部分。我以为 Crockford would have learned(仍然不是 perfect)。
【解决方案2】:

感谢 cmets 和回复,将兰特的回答延伸到我认为完全解释情况的内容。

JavaScript 函数当然是一个对象,当你实例化一个函数对象的新实例时,创建的对象会接收该函数的原型。

例如,

var Foo = fn() {
    this.ok= 'this is okay';
}

var Bar = fn(){};
Bar.prototype = new Foo(); // Bar.prototype is now a regular object, nothing fancy.

//for all intents and purposes, this is exactly like doing this :  
Bar.prototype = {ok : 'this is okay'}; //just assigns an object, reduntent

var test = new Bar(); //new Bar instance

console.log(test.ok); //prints 'bar'

有什么魔力?
test 没有ok 属性,但是当它被称为chains 时,直到function object's 原型并试图在那里找到它,如果它不能,它不断向上移动,直到到达终点。

再次感谢大家的回答

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多