我对javascript很新,试图理解基础知识。来自Python我有点不知所措的不同方法。
我想出了下面的模式来构建构造函数。我希望这是合理的做法:是吗?一些具体问题仍然存在:
_this = this
并仅使用_this
。这有什么害处吗?很抱歉我的问题不是很具体,但在这个阶段我需要一些确认/批评。
var Omelette = function () {
var _this = this;
_this.publicName = 'Dexter';
_this.publicEggs = 6;
// Override property values with custom supplied values
// This comes after the default values and before they are used
for (var p in arguments[0]) {
_this[p] = arguments[0][p];
}
var privateGreeting = 'Hello, ';
_this.publicSayHi = function () {
console.log(privateGreeting + _this.publicName );
};
var privateBreakEggs = function (brokenEggs) {
_this.publicEggs = _this.publicEggs - brokenEggs;
};
// initializing the prototype breaks two eggs
privateBreakEggs(2);
console.log(_this.publicEggs);
};
var myOmelette = new Omelette({
publicName: 'Roy'
});
// 4
var hisOmelette = new Omelette({
publicEggs: 12
});
// 10
hisOmelette.publicSayHi();
// Hello Dexter
hisOmelette.publicEggs = 12;
// No more eggs are broken
console.log(myOmelette.publicEggs);
// These are unchanged
hisOmelette.breakEggs();
// not publicly accessible. error 'undefined is not a function'
答案 0 :(得分:0)
看看以下代码:
var Omelette = function (overrideObject) {
this.publicName = 'Dexter';
this.publicEggs = 6;
// Override property values with custom supplied values
if (overrideObject)
{
var keys = Object.keys(overrideObject); //get all the keys from the override object.
//We use Object.keys for this. -> puts all the keys of an object into an array.
for (var i = 0; i < keys.length; ++i)
{
this[keys[i]] = overrideObject[keys[i]]; //loop over every key and overwrite/set the value a public variable.
}
}
var privateGreeting = 'Hello, ';
this.publicSayHi = function () {
console.log(privateGreeting + this.publicName ); //this refers to the instance created and the owner of function publicSayHi.
};
var privateBreakEggs = function (brokenEggs) {
this.publicEggs = this.publicEggs - brokenEggs;
};
this.breakEggs = privateBreakEggs; //reference to privateBreakEggs, making it publically available.
//this won't work since the this in privateBreakEggs refers to its own scope.
privateBreakEggs(2);
//this will work since it's called via `this`.
this.breakEggs(2);
};
var myOmelette = new Omelette({
publicName: 'Roy'
});
myOmelette.publicSayHi(); //should say Roy.
var hisOmelette = new Omelette({
publicEggs: 12
});
hisOmelette.publicSayHi(); //should say Dexter
console.log(hisOmelette.publicEggs); //10
console.log(myOmelette.publicEggs); //4
// These are unchanged
hisOmelette.breakEggs(2); //eggs now 8
console.log(hisOmelette.publicEggs)
hisOmelette.privateBreakEggs
// not publicly accessible. 'undefined'
&#13;
我对您的代码进行了一些更改并进行了评论。将它与您自己的代码进行比较,并从差异中学习。我不再引入_this
变量,因为它不必要。
使用参数覆盖实例的默认属性没有任何缺点。可以在创建后添加到实例中,现在在创建期间添加它们。您的方法(由我改进)允许在创建实例时轻松创建属性。请记住,属性仅在该实例上设置。如果您希望与所有实例共享它们,请使用原型。