【发布时间】:2015-05-27 19:09:51
【问题描述】:
以下工作并满足我的需要。但是,有没有更好的方法来引用“c:”中的“a”和“b”?
<html>
<head>
<script type="text/javascript">
var bar;
function Foo() {}
Foo.prototype = {
a: 1,
b: 2,
c: function() {
return Foo.prototype.a + Foo.prototype.b;
}
}
bar = new Foo();
console.log('c is: ' + bar.c());
</script>
</head>
<body>
<button onclick="document.write('c is: ' + bar.c())">Try it</button>
</body>
</html>
【问题讨论】:
-
我总是这样做
this.a和this.b -
另外,如果它重要的话,idk,但如果你有一个方便的方法,而不是用新对象破坏 Foo.prototype,你可能想要使用 extend() 或 mixin() 方法。
-
那么,您需要什么?它应该如何与继承一起工作?你为什么要把数据属性放在原型上?
-
看来我把这个问题搞砸了。问题是当函数被实例化为匿名函数时。在这种情况下,没有定义“this”。谢谢大家,但要关闭它。
标签: javascript variables initialization self-reference