如何在javascript中为对象编写原型函数?

Nez*_*zih 1 javascript prototype object

有可能做出这样的事吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何在我的原型方法中使用对象(在本例中为foo和bar).另外我想使用它像属性而不是函数,否则它看起来像这样

foo.isNotEmpty() && "foo is not empty"
Run Code Online (Sandbox Code Playgroud)

我更喜欢第一种方式,但如果不可能的第二种方式也可以.谢谢你的帮助.

T.J*_*der 5

我不知道如何在我的原型方法中使用对象(在本例中为foo和bar).

this在函数中使用.

但是:

  1. 从来没有永远添加可枚举的属性Object.prototype(这是什么Object.prototype.isNotEmpty = ...).你将打破大量代码,假设for-inon {}将看不到任何要访问的属性/ Object.keys({})将返回一个空数组.如果你真的想这样做,请使用Object.defineProperty并且不要设置enumerabletrue(默认为false,所以如果你把它关掉,那就很好).

  2. Object.prototype通常强烈建议不要添加非可枚举属性,因为可能会与对象的预期"自有"属性发生冲突.

  3. 您需要在调用它之前添加它.在您的代码中,您在添加它之前尝试访问它.

  4. 要在不使用的情况下获得所需的结果(),您需要将该函数定义为属性getter(更多内容见下文).

所以你可以这样做(使用非getter函数):

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());
Run Code Online (Sandbox Code Playgroud)

......或者如果你想要一个吸气剂:

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);
Run Code Online (Sandbox Code Playgroud)

通常最好有自己的函数(在一个范围构造中[未显示],所以你没有定义一个全局):

function isNotEmpty(obj) {
    return Object.keys(obj).length == 0;
}

let foo = {}, bar = {name : "carl"};
console.log(isNotEmpty(foo));
console.log(isNotEmpty(bar));
Run Code Online (Sandbox Code Playgroud)