面向对象的 JavaScript 帮助
我有以下代码:
var HD = function() { };
HD.Car = (function() {
var _date = "09/07/2010";
return {
Make: undefined,
Model: undefined,
showMakeAndModel: function() {
document.write(this.Make + " " +
this.Model +
" (data correct as of " + _date + ")");
}
};
})();
var bert = new HD.Car();
bert.Make = "Ford";
bert.Model = "Capri";
window.onload = bert.showMakeAndModel();
并收到以下错误:
HD.Car 不是构造函数
我想做的就是测试(学习)带有闭包(对于私有成员)的“单例模式”,所以不是一个“真实”的例子,但我正在阅读的书表明这是这样做的方法。
所以有点困惑 - 任何帮助将不胜感激.. 抢
I have the following code:
var HD = function() { };
HD.Car = (function() {
var _date = "09/07/2010";
return {
Make: undefined,
Model: undefined,
showMakeAndModel: function() {
document.write(this.Make + " " +
this.Model +
" (data correct as of " + _date + ")");
}
};
})();
var bert = new HD.Car();
bert.Make = "Ford";
bert.Model = "Capri";
window.onload = bert.showMakeAndModel();
And get the following error:
HD.Car is not a constructor
All I'm trying to do is test (to learn) the 'singleton pattern' with closure (for private members) so not a 'real' example, but the book I'm reading suggests this is the way to do it.
So a little confused - any help would be much appreciated..
Rob
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
HD.Car 类定义周围有一些不正确的 ()() 。这个固定示例的工作原理:
You have some incorrect ()() around the HD.Car class definition. This fixed sample works:
有关更多信息:
如何用javascript编写单例类。
希望这能为您带来更多启发!
For a bit more info:
How to write a singleton class in javascript.
Hopefully that will shed a bit more light for you!
在 JavaScript 中,您只能将 new 关键字与函数结合使用。
HD.Car
不是一个函数,它是一个对象。只是不要在您的示例中使用
new
。In JavaScript you can only use the new keyword with functions.
HD.Car
is not a function, it's an object.Just don't use
new
for your example.您的错误来自于您正在执行构造函数这一事实,如 HD.Car 声明之后(以及 var bert 之前)的左括号和右括号所示。因此,该函数正在执行并返回一个对象,然后您尝试将其与“new”运算符一起使用。
如果删除这些括号,我相信您会获得所需的功能。
Your error is coming from the fact that you're executing your constructor function, as indicated by the open and close parentheses after the declaration of HD.Car (and just before var bert). So, the function is executing and returning an object, which you're then trying to use with the "new" operator.
If you remove those parentheses, I believe you'll get the functionality you want.
删除
new
,因为只有构造函数需要它。现在,HD.Car 将成为匿名且自动执行函数返回的对象。然后删除 HD.Car 之后的括号。所以它应该看起来像:现在 HD.Car 是一个
单例
。如果你希望它更像一个工厂,你应该这样做:
Remove
new
, because it is only needed for constructor functions. Now HD.Car will be the object that an anonymous and self-executing function returns. Then remove parens after HD.Car. So it should look like:Now HD.Car is a
singleton
.If you want it to be more like a
factory
you should do: