简体   繁体   中英

How to write prototype function for object in javascript?

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.

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 :

  1. 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).

  2. Even adding non-enumerable properties to Object.prototype is generally strongly discouraged, because of potential conflicts with expected "own" properties of objects.

  3. You need to add it before you call it. In your code, you're trying to access it before you've added it.

  4. 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)); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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