我希望能夠學習按照新的JavaScript ECMA 5標準創建對象,並在我的當前項目中使用它們,而不會破壞功能。但我看到未解釋的東西,這讓我害怕Object.create而不是構造函數繼承
考慮下面的代碼:
var foo = {
oldProp: 'ECMA Script 3',
newProp: 'ECMA Script 5'
};
// The new way of inheritance
var bar = Object.create(foo);
// and of assigning properties, if I am right
var bar2 = Object.create(Object.prototype, {
oldProp: { value: 'ECMA Script 3'},
newProp: { value: 'ECMA Script 5'}
});
// and then
bar;
// console output
Object {oldProp: "ECMA Script 3", newProp: "ECMA Script 5"}
// whereas !!
bar2;
Object {} // Why this?
此外,
bar.hasOwnProperty('oldProp'); // false, whereas
bar2.hasOwnProperty('oldProp'); // true !! It should be the other way round, right?
另外,我不能夠改變的bar2
bar2.oldProp = "Marry had a little lamb";
bar2.oldProp; // "ECMA Script 3"
還有更多 -
for (k in bar2) console.log(bar2[k]) // undefined
上午我以正確的方式創建的對象? 我基本上想要實現的是擺脫構造函數。
舊代碼:
var Slideshow = function(type) {
this.type = type;
this.deleteSlideshow = function() {
// some code
}
}
Slideshow.prototype.nextSlide = function() {
// lotsa code
}
var vanityFairSlideshow = new Slideshow('wide-screen');
我想更改爲Object.create
,可能是一種這樣的:
var Slideshow = Object.create({ /* prototype */ }, { /* properties and methods */ });
var vanityFairSlideshow = Object.create(Slideshow , { /* properties and methods */ });
請告訴我這樣做的正確方法?
* *爲什麼你想擺脫建設者? – Bergi 2013-04-24 08:44:43
@Bergi,只是爲了學習現代JavaScript,強調相同。不要把我誤認爲叛徒隊友。對於詳細的解釋,我始終用構造函數的方式作爲結構體 – 2013-04-24 18:37:56