简体   繁体   English

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

[英]Javascript Object.defineProperty property has same name with method

I'm new to js world and find jquery declares many properties as methods which make me very uncomfortable.Such as $("#foo").parent() which i think should be a property. 我是js世界的新手,发现jquery声明了许多属性作为方法,这些方法使我非常不舒服。例如$("#foo").parent() ,我认为这应该是一个属性。

I know that js can also define property so i want to try redefine these method to corresponding property. 我知道js也可以定义属性,所以我想尝试将这些方法重新定义为相应的属性。

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

then i can use it like this $("#foo").parent 那么我可以像这样使用它$("#foo").parent

but i got a stackoverflow 但我有一个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)

What's happening here? 这里发生了什么事? In my mind, it should be possible for variables/property and methods to have the same name which i'm familiar with in other language such as c#,kotlin... 在我看来,变量/属性和方法应该具有与其他语言(例如C#,kotlin)相同的名称。

You're defining Object.parent to call himself, that's an infinite recursive loop. 您正在定义Object.parent来调用自己,这是一个无限的递归循环。

The reason why jQuery defines functions to get properties is that it computes dynamic values at runtime, using an oldish coding style (getters and setters exist only from ES5.1 specs ). jQuery定义用于获取属性的函数的原因是,它使用老式的编码样式(仅在ES5.1规范中存在getter和setter)在运行时计算动态值。 maybe what you could do is create shortcuts for those properties ( Object.prototype.par instead of parent ), but there's no effort on doing that IMHO. 也许您可以做的是为这些属性创建快捷方式( Object.prototype.par而不是parent ),但是您无需为此做任何努力。

here this.parent() is make calling function recursively. 在这里this.parent()使递归调用函数。 so give some other name to ur defined function something like getparent Object.defineProperty($.fn,"getparent", call this as $("#foo").getparent 因此为您定义的函数命名,例如getparent Object.defineProperty($.fn,"getparent",称其为$("#foo").getparent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM