Reputation: 379
is it possible to make something like this ?
let foo = {}, bar = {name : "carl"};
foo.isNotEmpty && "foo is not empty" // FALSE
bar.isNotEmpty && "bar is not empty"; // TRUE
Object.prototype.isNotEmpty = function (){
return Object.keys(_argument_here).length == 0;
}
I don't know how to use object (in this case foo and bar) in my prototype method. Also i want to use it like property not a function, otherwise it looks like this
foo.isNotEmpty() && "foo is not empty"
I prefer first way but if its not possible second way is okay too. Thanks for your help.
Upvotes: 1
Views: 220
Reputation: 1074048
I don't know how to use object (in this case foo and bar) in my prototype method.
You'd use this
within the function.
But:
Never, ever, ever add enumerable properties to Object.prototype
(which is what Object.prototype.isNotEmpty = ...
does). You'll break a huge amount of code that assumes that for-in
on {}
won't see any properties to visit / Object.keys({})
will return an empty array. If you really want to do it, use Object.defineProperty
and don't set enumerable
to true
(the default is false
, so if you just leave it off, you're good).
Even adding non-enumerable properties to Object.prototype
is generally strongly discouraged, because of potential conflicts with expected "own" properties of objects.
You need to add it before you call it. In your code, you're trying to access it before you've added it.
To get the result you want without using ()
, you need to define the function as a property getter (more on that below).
So you could do this (with a non-getter function):
Object.defineProperty(Object.prototype, "isNotEmpty", {
value: function (){
return Object.keys(this).length == 0;
},
configurable: true
});
let foo = {}, bar = {name : "carl"};
console.log(foo.isNotEmpty());
console.log(bar.isNotEmpty());
...or if you want a getter:
Object.defineProperty(Object.prototype, "isNotEmpty", {
get: function (){
return Object.keys(this).length == 0;
},
configurable: true
});
let foo = {}, bar = {name : "carl"};
console.log(foo.isNotEmpty);
console.log(bar.isNotEmpty);
But generally it would be better to have your own function (within a scoping construct [not shown] so you're not defining a global):
function isNotEmpty(obj) {
return Object.keys(obj).length == 0;
}
let foo = {}, bar = {name : "carl"};
console.log(isNotEmpty(foo));
console.log(isNotEmpty(bar));
Upvotes: 5
Reputation: 474
Object.defineProperty(
Object.prototype, 'isNotEmpty', {
get: function() {
return this.length > 0;
}
}
);
const a = 'test';
console.log(a.isNotEmpty); // true
As mentioned before, javascript is a strange language, please do not pollute prototypes.
Upvotes: 1