使用所有对象都可以使用的功能来增强 Object 对象
我增强 Object 的动机是希望能够轻松处理用于简单存储数据的对象(如 Java 中的“哈希图”)。我想轻松地执行 hashmap.size()。
假设我的对象有一个名为 objData 的属性,这样创建时该属性为空:
var objData = {};
我的对象有一些可以向 objData 添加数据的方法,如下所示:
this.objData[key1name] = data1;
我的对象也有一些访问 objData 的方法:
if(this.objData.size() == 0):
当然,不存在这样的方法。这就是我增强 Object 对象的动机:
Object.prototype.getOwnPropertyCount = function ( ) {
var count = 0;
for(var item in this) {
if (this.hasOwnProperty(item)) {
count += 1;
}
}
return count;
};
现在我应该能够执行以下任一操作:
if (this.objData.getOwnPropertyCount() == 0)
或:
if(!objData.getOwnPropertyCount())
但实际上,当我尝试加载与我编写的任何代码完全无关的页面时,我会收到错误。我在 google 地图 api 的 main.js 中遇到错误。巫毒。
因此,我更改了增强以增强实际的 Object 而不是 Object.prototype:
Object.getOwnPropertyCount = function ( ) {
//calculate the count
return count;
};
现在我在 Firefox 中收到以下错误:
this.objData.getOwnPropertyCount is not a function
我在这里缺少什么?
My motivation for the augmentation of Object is I want to be able to easily handle objects meant to simply store data (like a "hashmap" in Java). I want to easily do hashmap.size().
Let's say my object has a property called objData which was empty when made like this:
var objData = {};
My object has some methods that can add data to objData like this:
this.objData[key1name] = data1;
And my object also has some methods which access objData:
if(this.objData.size() == 0):
Of course, no such method exists. So that's my motivation for augmenting the Object object:
Object.prototype.getOwnPropertyCount = function ( ) {
var count = 0;
for(var item in this) {
if (this.hasOwnProperty(item)) {
count += 1;
}
}
return count;
};
Now I should be able to do either:
if (this.objData.getOwnPropertyCount() == 0)
or:
if(!objData.getOwnPropertyCount())
But in actuality I get errors when I try to load the page completely unrelated to any code I've written. I'm getting errors thrown in google maps api's main.js. Voodoo.
So I change my augmentation to augment the actual Object instead of Object.prototype:
Object.getOwnPropertyCount = function ( ) {
//calculate the count
return count;
};
And now I get the following error in Firefox:
this.objData.getOwnPropertyCount is not a function
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将方法声明从
Object.prototype
直接移至Object
构造函数时,该方法在所有对象的原型链中不再可用(顺便说一句,这是一件好事),我建议您为您的函数提供一个参数,以传递您需要操作的对象,并更改您的方法调用:显然,在您的实现中,您应该计算所传递对象的属性,因为
this,将引用
对象
构造函数,在上面的例子中。When you move your method declaration from
Object.prototype
directly to theObject
constructor, the method is no longer available in the prototype chain of all objects (a good thing BTW), I would suggest you to provide your function an argument, to pass the object you need to opearate, and change your method call:And obviously, in your implementation, you should count the properties of the passed object, since
this
, will refer to theObject
constuctor, in the above example.