<分区>
我正在尝试理解面向对象的 JavaScript 并坚持使用一些示例。它们似乎有点不同的传统 OOP。
首先,与那些有什么区别:
function Foo()
{
this.bar = function ()
{
// ...
};
}
对比
function Foo() {}
Foo.prototype.bar = function()
{
// ...
}
另外,我应该使用哪一个?哪一个是正确的方法?
工厂模式的另一个例子。
function Circle()
{
this.say = function() { console.log('I am circle.'); };
}
function Square()
{
this.say = function() { console.log('I am square.'); };
}
function chooseShape(decision)
{
var shape = null;
if (decision === "Circle")
{
shape = Circle; // or Circle.prototype.constructor;
} else if (decision === "Square")
{
shape = Square; // or Square.prototype.constructor;
}
return new shape();
}
如果我用这些改变这些行:
if (decision === "Circle")
{
shape = Circle.prototype.constructor;
} else if (decision === "Square")
{
shape = Square.prototype.constructor;
}
它们按预期工作,但我想知道引擎盖下发生了什么。