[英]Triple nested object functions js
我有一個主要由函數/方法組成的對象,很像這樣(應該可以工作!):
function thing1(){
this.thing2 = function(){
this.thing3 = function(){
alert();
}
}
}
但
當我調用thing1.thing2.thing3()
,我得到
無法讀取未定義的屬性“thing3”
完整的偽代碼:
function thing1(){
this.thing2 = function(){
this.thing3 = function(){
alert();
}
}
}
var foo = new thing1();
foo.thing2.thing3();
這些是構造函數:
function thing1(){ this.thing2 = function(){ this.thing3 = function(){ alert(); } } } (new (new thing1()).thing2()).thing3()
如果你想調用thing1.thing2.thing3()
你應該這樣格式化:
function thing1(){ this.thing2 = { thing3: function(){ alert(); } } } var foo = new thing1(); foo.thing2.thing3()
thing2
不返回導致返回undefined
任何內容。
如果你想寫鏈接功能,您需要返回this
:
function thing1() {
this.thing2 = function() {
this.thing3 = function() {
alert();
}
return this; // chained
}
}
一般來說,如果您打算將其用作構造函數,最好將方法分配給函數原型。 您仍然可以在原型上鏈接函數。
function thing1() { } thing1.prototype.thing2 = function() { return this; // chained }; thing1.prototype.thing3 = function() { alert('thing3'); return this; // you can make this one chained as well, if you like }; var t = new thing1(); t.thing2().thing3().thing2().thing3();
如果您只想創建一個不需要括號的基本鏈,您可以創建一個單獨的getter 函數。
function thing1() { } Object.defineProperty(thing1.prototype, 'thing2', { get: function() { return this; } }); thing1.prototype.thing3 = function() { alert('thing3'); return this; }; var foo = new thing1(); foo.thing2.thing3().thing2.thing3();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.