简体   繁体   English

你能在Javascript中创建一个不从Object继承的对象吗?

[英]Can you make an object in Javascript which does NOT inherit from Object?

Occasionally there is a JS framework or library that thinks it's a really wise idea to add some net new features to the prototype of Object or Array . 偶尔有一个JS 框架或库认为向ObjectArray的原型添加一些新的新功能是一个非常明智的想法。 I can't find any more examples right now, but I do remember that I've had problems with that before. 我现在找不到更多的例子了,但我记得以前我遇到过这个问题。 Of course, doing so breaks the good old for(...in...) loop, because suddenly those properties are now enumerated too. 当然,这样做会打破for(...in...)循环的好处,因为突然现在也枚举了这些属性。 To get around it you have to check every enumerated property with .hasOwnProperty() before accessing. 要绕过它,您必须在访问之前使用.hasOwnProperty()检查每个枚举属性。 Which is cumbersome, when trying to write robust code. 在尝试编写健壮的代码时,这很麻烦。

So I got wondering - is there some way that I could make my own objects so, that they don't inherit from Object ? 所以我想知道 - 有什么方法可以让我自己创建自己的对象,它们不会从Object继承吗? Initial playing around with .prototype yielded no results. 最初玩.prototype没有产生任何结果。 Perhaps there is some trick to it? 也许有一些技巧呢? Or will everything always inherit from Object and there's nothing I can do about it? 或者一切都会从Object继承而且我无能为力吗?

Added: I guess I should have noted that I want it for client-scripts in browsers, and compatibility should include IE6, or at least IE7. 补充:我想我应该注意到我想要它用于浏览器中的客户端脚本,并且兼容性应该包括IE6,或者至少IE7。 Other browser version requirements are more lenient, though the more the better, of course. 其他浏览器版本要求更宽松,当然越多越好。 (Yes, sadly, the corporate world still lives in IE-world...) (是的,遗憾的是,企业界仍然生活在IE世界......)

In ECMAScript 5 you can pass null to Object.create : 在ECMAScript 5中,您可以将null传递给Object.create

> obj = Object.create(null);
  Object
    No Properties

You can explicitly remove any Object properties that are enumerable, but moderen browsers allow nonenumerable Object methods. 您可以显式删除任何可枚举的Object属性,但moderen浏览器允许使用不可数的Object方法。

Should work in older browsers though. 应该在旧版浏览器中工作。

function Myobject(props){
}
var O=Object,OP=Object.prototype;
for(var p in O)delete Myobject[p];
for(var p in OP)delete Myobject.prototype[p];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM