Object.create而不是Constructors用于继承 [英] Object.create instead of Constructors for inheritance
问题描述
我希望能够学习按照新的JavaScript ECMA 5标准创建对象,并在我当前的项目中使用它们,而不会破坏功能。但我看到让我害怕的不可解释的东西
I want to be able to learn creating Objects per the new JavaScript ECMA 5 standards, and use them in my current projects, without breaking functionality. But I see un-explainable stuff that makes me afraid
请考虑以下代码:
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 $的属性c $ c>
bar2.oldProp = "Marry had a little lamb";
bar2.oldProp; // "ECMA Script 3"
还有更多 -
for (k in bar2) console.log(bar2[k]) // undefined
我是否以正确的方式创建对象?
我基本上想要实现的是摆脱构造函数。
Am I creating the Objects in a correct way? What I basically want to achieve is getting rid of constructors.
旧代码:
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
,可能是这样的:
I want to change to Object.create
, may be kind of this:
var Slideshow = Object.create({ /* prototype */ }, { /* properties and methods */ });
var vanityFairSlideshow = Object.create( Slideshow , { /* properties and methods */ });
这样做的正确方法是什么?
Whats the proper way of doing it?
推荐答案
这里的问题是描述符(除了值
)。
Your problem here is the defaults for the descriptors (aside from value
) that you omitted for each property.
使用此语法(例如 defineProperty
和 defineProperties
), 可写
false
默认情况下, 可枚举
false
。
Using this syntax (like for defineProperty
and defineProperties
), writable
is false
by default, and enumerable
is false
.
将这两者设置为 true
将导致您期望的行为。
Setting both of these to true
will result in the behaviour you expect.
var bar2 = Object.create( Object.prototype, {
oldProp: { value: 'ECMA Script 3', writable: true, enumerable: true}
});
此外,希望您了解所有浏览器都不支持此功能;请注意 <$ c $的兼容性表C>的Object.create 。 可写
和可配置
属性的垫片不存在,也不存在。
Also, hopefully you appreciate how this isn't supported in all browsers; note the compatibility table for Object.create
. Shims which adhere to the writable
and configurable
properties do not, and cannot, exist.
最后,+1这样一个写得很好的问题;这是一股清新的空气。
这篇关于Object.create而不是Constructors用于继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!