是否可以嵌套JavaScript对象?

时间:2014-01-28 17:35:47

标签: javascript class oop object nested

似乎这是不可能的。还有另一种巧妙的方法来实现这个目标吗?

// Our transitions class
function Transitions() {
    this.fade = function() {
            this.create = function() {
                alert('you have arrived at the create method of the fade class');
            }
    }
}

1 个答案:

答案 0 :(得分:3)

这是可能的。你现在使用它的方式。

您可以这样做来调用创建函数:

var x = new Transitions();
// Here .create does not exists
x.fade(); // Here the create function will be generated to the this object
x.create(); // Does alert

但你可能想要这样的东西:

function Transitions() {
        // Create an object with an sub object
        this.fade = {
                create : function() {

                    alert('you have arrived at the create method of the fade class');
                }
        }

    }

var x = Transitions();
x.fade.create(); // Call the sub object