Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript nodeJS中的对象扩展_Javascript_Node.js - Fatal编程技术网

Javascript nodeJS中的对象扩展

Javascript nodeJS中的对象扩展,javascript,node.js,Javascript,Node.js,可以在JavaScript中使用对象扩展吗?比如说 Extensions.js function any.isNullOrEmpty() { if (this == null || this == "") { return true } return false } app.js var x = "" console.log(x.isNullOrEmpty()) //should log true 这可能吗?我该怎么做?您可以使用Object.prototype在Jav

可以在JavaScript中使用对象扩展吗?比如说

Extensions.js

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

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

这可能吗?我该怎么做?

您可以使用
Object.prototype
在JavaScript中扩展这种类型的功能

Object.prototype.isNullOrEmpty=function(){
如果(this==null | | this==“”){
返回真值
}
返回错误
}
var x=“”;
x、 isNullOrEmpty();//返回true

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

…但是,因为是一个不能有方法的原语,所以我能想到的使目标为
null
的唯一方法是使用
call
apply
bind

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

'use strict'//对于'call'和'null'的使用很重要`
Object.prototype.isNullOrEmpty=function(){返回this===null | | this.valueOf()==='''}
常数s=''
console.log(s.isNullOrEmpty())
常数t=null
console.log(Object.prototype.isNullOrEmpty.call(t))

您需要将您的自定义方法添加到对象或数组的属性类型中,或者添加您想要在其上使用方法的所有内容

但在您的情况下,您需要像下面这样编写代码:

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

console.log(a.isNullOrEmpty())

这是可行的,但是在代码中检查
null
是无用的,因为
null.isNullOrEmpty()
不起作用。我正在演示如何使用Prototype扩展对象功能。我使用了op提供的代码:)还要注意,对原语使用属性访问会导致装箱
Object.prototype.isEmpty=function(){返回this==“”;};console.log((“”).isEmpty())
可能会产生意想不到的结果。嘿@hardcode,作者的问题更多的是关于如何扩展字符串本身的功能,因为必须在
原型
链上扩展它,如这里的另一个答案所示。如果采用,将允许更容易地对给定对象使用自由方法。例如,如果
isNullOrEmpty
被定义为一个普通函数,那么您可以将其称为
variable::isNullOrEmpty()
,这类似于
isNullOrEmpty.call(variable)
哦,谢谢,有没有办法将其放在不同的文件中,然后将其导入其他文件?如果这是生产代码,我只需将该方法公开为一个实用程序,并将其用作
isNullOrEmptyString(o)
。节点具有内置的模块化功能。另外:您可能不需要此函数,因为有许多技术可用于处理假值,例如使用
|
布尔运算符或三元运算符(尽管这些运算符通常也会匹配
未定义的
)。
function validateValue(value){

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

    }

}