javascript - 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
这可能吗?我该怎么做?
解决方案
您可以向Object
原型添加一个方法,并使用该valueOf
方法获取字符串的值:
...但是,因为null
是一个不能有方法的原语,所以我能想到的唯一方法null
是使用call
,apply
或bind
.
但是你永远不会在生产代码中这样做,因为不鼓励修改内置对象的原型。
'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))
推荐阅读
- excel - VBA - 如何在 Excel 工作表的名称末尾创建没有 (2) 的同名 Excel 工作表?
- java - 为 Apache Camel Http 组件禁用或设置 SSL
- c++ - 当键值作为输入时打印无序映射值
- sql - SQL 存储过程更新循环
- php - 如何在不使用重新排序的键号的情况下循环遍历 php/laravel 中的重新排序的数组
- javascript - asp中select的使用值
- wordpress - 自定义帖子类型的常用分类页面
- python - 使用源为 MYSQL 的 Python 检索上个月的数据
- video - HTML
- netlogo - Netlogo:减去以前扩散的值