[英]Triple nested object functions js
I have an object mainly composed of functions/ methods, much like this (Which should work!):我有一个主要由函数/方法组成的对象,很像这样(应该可以工作!):
function thing1(){
this.thing2 = function(){
this.thing3 = function(){
alert();
}
}
}
But但
When I call thing1.thing2.thing3()
, I get当我调用
thing1.thing2.thing3()
,我得到
Cannot read property 'thing3' of undefined无法读取未定义的属性“thing3”
complete pseudocode:完整的伪代码:
function thing1(){
this.thing2 = function(){
this.thing3 = function(){
alert();
}
}
}
var foo = new thing1();
foo.thing2.thing3();
Those are constructors:这些是构造函数:
function thing1(){ this.thing2 = function(){ this.thing3 = function(){ alert(); } } } (new (new thing1()).thing2()).thing3()
If you want to call thing1.thing2.thing3()
you should format it like this:如果你想调用
thing1.thing2.thing3()
你应该这样格式化:
function thing1(){ this.thing2 = { thing3: function(){ alert(); } } } var foo = new thing1(); foo.thing2.thing3()
thing2
doesn't return anything which results in returning undefined
. thing2
不返回导致返回undefined
任何内容。
If you want to write chained functions, you need to return this
:如果你想写链接功能,您需要返回
this
:
function thing1() {
this.thing2 = function() {
this.thing3 = function() {
alert();
}
return this; // chained
}
}
Generally speaking, it's better to assign methods to a functions prototype if you intend to use it as a constructor.一般来说,如果您打算将其用作构造函数,最好将方法分配给函数原型。 You can still chain functions on the prototype.
您仍然可以在原型上链接函数。
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();
If you want to just create a basic chain without requiring parentheses, you could create a separate getter function .如果您只想创建一个不需要括号的基本链,您可以创建一个单独的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.