wiliamks
wiliamks

Reputation: 15

Object extensions in nodeJS

Is it possible to have object extensions in JavaScript? For example

Extensions.js

function any.isNullOrEmpty() {
  if (this == null || this == "") {
     return true
  }
  return false
}

app.js

var x = ""
console.log(x.isNullOrEmpty()) //should log true

is this possible? How do I do it?

Upvotes: 0

Views: 142

Answers (4)

HardCode
HardCode

Reputation: 1

function validateValue(value){

    function isNullEmpty(){
          return (value === void (0) || value == null)
    }
    return { isNullOrEmpty }

    }

}

Upvotes: 0

Mahdi Ashouri
Mahdi Ashouri

Reputation: 562


you need to add your custom method into prop type of object or array or everything u want to use your method on it.

but in your case you need to this like code below:

Object.prototype.isNullOrEmpty = function(){
  if (this === null || this == "") {
       return true
  }
  return false
}
 let a = {a:'10'}

console.log(a.isNullOrEmpty())

Upvotes: 0

Ben Aston
Ben Aston

Reputation: 55739

You could add a method to the Object prototype, and use the valueOf method to get the value of the string:

...but, because null is a primitive that cannot have a method, the only way I can think of to get the target to be null would be to use call, apply or bind.

But you would never do this in production code, because modifying the prototype of built-in objects is discouraged.

'use strict' // important for the use of `call` and `null`

Object.prototype.isNullOrEmpty = function() {  return this === null || this.valueOf() === '' }

const s = ''
console.log(s.isNullOrEmpty())

const t = null
console.log(Object.prototype.isNullOrEmpty.call(t))

Upvotes: 1

steadweb
steadweb

Reputation: 16541

You could use Object.prototype to extend this type of functionality in JavaScript.

Object.prototype.isNullOrEmpty = function() {
  if (this == null || this == "") {
     return true
  }
  return false
}

var x = "";

x.isNullOrEmpty(); // returns true

Upvotes: 0

Related Questions