这样的事情可能吗?
function Sleep(date) {
this.Date = date || null;
this.TimeWakeUp =
this.PercAwake =
this.MoodAfterAwake =
this.Naps =
this.TimeToBed =
this.MoodToBed =
null;
}
Object.defineProperty(Sleep, 'MoodAfterAwake', {
__proto__: {
options: [
"bla",
"bla",
"bla",
"bla"
]
}
});
基本上我希望Sleep构造函数的一个属性继承原型,所以即使Sleep.MoodAfterAwake为null或未定义,我仍然可以访问Sleep.MoodAfterAwake.options。
答案 0 :(得分:0)
正如JavaScript所说:您可以访问null / undefined的任何属性。所以这是不可能的。此外,您可以检查https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
答案 1 :(得分:0)
你的意思是这样吗
function Sleep(date) {
this.Date = date || null;
this.TimeWakeUp =
this.PercAwake =
this.MoodAfterAwake =
this.Naps =
this.TimeToBed =
this.MoodToBed =
null;
}
Sleep.prototype.moodAfterAwake = ["bla","bla","bla"]
然后您可以像
一样访问它var a = new Sleep()
a.moodAfterAwake[3];
或者如果要将属性附加到Sleep函数,则无需原型。函数也是对象,可以具有属性。
就这样做
Sleep.moodAfterAwake = ["bla","bla","bla"]