[英]Why i can't access an object created in a method of an object
假设我有以下代码:
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
方法之外工作?
更改您的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)
obj是函数create的局部变量。 您需要返回它以提供对该函数外部的访问。
var t =
{
create: function()
{
var obj = Object.create(m);
obj.init(1,2,3);
return obj;
}
};
var obj = t.create();
console.log(obj)
返回创建的对象将解决您的问题。 obj是绑定到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;
}
};
let obj = t.create();
console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.