簡體   English   中英

Javascript Object.defineProperty屬性與方法具有相同的名稱

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

我是js世界的新手,發現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)相同的名稱。

您正在定義Object.parent來調用自己,這是一個無限的遞歸循環。

jQuery定義用於獲取屬性的函數的原因是,它使用老式的編碼樣式(僅在ES5.1規范中存在getter和setter)在運行時計算動態值。 也許您可以做的是為這些屬性創建快捷方式( Object.prototype.par而不是parent ),但是您無需為此做任何努力。

在這里this.parent()使遞歸調用函數。 因此為您定義的函數命名,例如getparent Object.defineProperty($.fn,"getparent",稱其為$("#foo").getparent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM