我希望能够学习根据新的 JavaScript ECMA 5 标准创建对象,并在我当前的项目中使用它们,而不会破坏功能。但我看到无法解释的东西让我害怕
考虑以下代码:
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 */ });
这样做的正确方法是什么?