首页 > 解决方案 > nodeJS 中的对象扩展

问题描述

是否可以在 JavaScript 中进行对象扩展?例如

Extensions.js

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

应用程序.js

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

这可能吗?我该怎么做?

标签: javascriptnode.js

解决方案


您可以向Object原型添加一个方法,并使用该valueOf方法获取字符串的值:

...但是,因为null是一个不能有方法的原语,所以我能想到的唯一方法null是使用call,applybind.

但是你永远不会在生产代码中这样做,因为不鼓励修改内置对象的原型。

'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))


推荐阅读