[英]Why i can't access an object created in a method of an object
Let's say i have this code: 假设我有以下代码:
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)
When executing this code i get this error: 执行此代码时出现此错误:
obj is not defined
obj未定义
How can I make obj
work outside the method create
? 如何使
obj
在create
方法之外工作?
Change your create
function to return the obj
. 更改您的
create
函数以返回obj
。 Then, you can do var obj = t.create()
. 然后,您可以执行
var obj = t.create()
。
Here is the complete code: 这是完整的代码:
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 is a local variable to the function create. obj是函数create的局部变量。 You need to return it to provide access to it outside of that function.
您需要返回它以提供对该函数外部的访问。
var t =
{
create: function()
{
var obj = Object.create(m);
obj.init(1,2,3);
return obj;
}
};
var obj = t.create();
console.log(obj)
Returning the object created would solve your issue. 返回创建的对象将解决您的问题。 The obj is a local variable bound to the scope of the create function you cannot access it outside.
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.