Javascript Object.defineProperty属性与方法具有相同的名称

时间:2017-11-06 14:51:45

标签: javascript jquery

我是js world的新手,并且发现jquery声明了很多属性作为让我感到非常不舒服的方法。比如$("#foo").parent()我觉得应该是属性。

我知道js也可以定义属性,所以我想尝试将这些方法重新定义为相应的属性。

Object.defineProperty($.fn,"parent",
        {
            get:function () {
                return this.parent()
            },
            configurable:false,
            enumerable:true
        });

然后我可以像$("#foo").parent

一样使用它

但我得到了一个stackoverflow

jqueryplus.js:180 Uncaught RangeError: Maximum call stack size exceeded
    at n.fn.init.get [as parent] (jqueryplus.js:180)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)
    at n.fn.init.get [as parent] (jqueryplus.js:181)

这里发生了什么?在我看来,变量/属性和方法应该可以使用我熟悉的其他语言相同的名称,例如c#,kotlin ......

2 个答案:

答案 0 :(得分:1)

您正在定义Object.parent来称呼自己,这是一个无限的递归循环。

jQuery定义函数以获取属性的原因是它使用旧的编码风格(运算符和设置器仅存在于ES5.1 specs)在运行时计算动态值。也许您可以做的是为这些属性创建快捷方式(Object.prototype.par而不是parent),但是没有努力去做恕我直言。

答案 1 :(得分:0)

这里this.parent()是递归调用函数。所以给你定义的函数提供一些其他名称,例如getparent Object.defineProperty($.fn,"getparent",,将其称为$("#foo").getparent

相关问题