首页 > 解决方案 > 为什么我无法访问在对象的方法中创建的对象

问题描述

假设我有这个代码:

var m = 
{
    init: function(num, num2, num3)
    {
        this.num = num;
        this.num2 = num2;
        this.num3 = num3;
    }
};

var t = 
{
    create: function()
    {
        var obj = Object.create(m);
        obj.init(1,2,3);
    }

};

t.create();
console.log(obj)

执行此代码时,我收到此错误:

obj 未定义

我怎样才能obj在方法之外工作create

标签: javascriptjavascript-objects

解决方案


更改您的create函数以返回obj. 然后,你可以做var obj = t.create().

这是完整的代码:

var m = 
{
    init: function(num, num2, num3)
    {
        this.num = num;
        this.num2 = num2;
        this.num3 = num3;
    }
};

var t = 
{
    create: function()
    {
        var obj = Object.create(m);
        obj.init(1,2,3);
        return obj;
    }

};

var obj = t.create();
console.log(obj)

推荐阅读