javascript 擷取調用屬性的對象

來源:互聯網
上載者:User

標籤:

最近碰到一個javascript 的小問題,是和閉包有關的,來自cnode 論壇,很有意思。

    var o = (function() {        var person = {            name: ‘Vincent‘,            age: 24        };        return {            run: function(k) {                return person[k];            }        }    })();    // TODO 在不改變上面代碼的基礎上,並且在只知道 person 是一個對象的基礎上    // 只能在本段注釋後面繼續寫代碼,最終通過 o 列印出 person ,對於上文中的 person 即 `Object {name: "Vincent", age: 24}`    // 例如 o.someThing = 1; cosnole.log(o.run(‘someThing‘));    // 在考慮到 person 為未知對象的基礎上,儘可能寫出更加完善的代碼。    // 最終,如果不能完成該題,請儘可能的記錄下來你思考的過程。
View Code

上面就是完整的題目。

藉助object.prototype.__defineGetter__()可以實現這個功能。

  Object.prototype.__defineGetter__("getClosureVariable", function(){             return this;//可以返回調用這個屬性的對象                                             });                                                                         var person = o.run("getClosureVariable");                                   console.log(person);                                                      

__defineGetter__()的其它應用,例如,擷取一個文件項目的tagname

    HTMLElement.prototype.__defineGetter__("myTagName",function(){            return this.tagName;                                              })                                                                      console.log(document.getElementById("mySpan").myTagName);       
<span id="mySpan"></span>      

 

javascript 擷取調用屬性的對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.