英文:
Unable to access internal object after instantiation
问题
我有一个非常简单的代码,其中有已实例化的对象,我通过原型暴露了一些方法。以下是代码:
const MyClass = (function() {
function MyClass() {
this._obj = {
1: 'dfvdfvd'
};
}
function get() {
return this._obj[1];
}
MyClass.prototype.take = () => {
get.call(this);
}
return MyClass;
}());
let x = new MyClass();
console.log(x.take())
但是,我一直得到 _obj
为 undefined
。我在这里漏掉了什么?
英文:
I have a very simple code with instantiated objects and I'm exposing some methods via a prototype. Here's the code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const MyClass = (function() {
function MyClass() {
this._obj = {
1: 'dfvdfvd'
};
}
function get() {
return this._obj[1];
}
MyClass.prototype.take = () => {
get.call(this);
}
return MyClass;
}());
let x = new MyClass();
console.log(x.take())
<!-- end snippet -->
but I keep getting _obj
as undefined
. what am I missing here?
答案1
得分: 1
问题在于MyClass.prototype.take
是一个箭头函数,但箭头函数没有它们自己的this
(参见MDN),因此this
是默认的window
,而this._obj
是undefined
。你可以要么手动绑定它,要么像下面我所做的那样将其变成常规函数。
另外,请确保从MyClass.prototype.take()
返回一个值,否则你会得到undefined
。
const MyClass = (function() {
function MyClass() {
this._obj = {
1: 'dfvdfvd'
};
}
function get() {
return this._obj[1];
}
MyClass.prototype.take = function() {
return get.call(this);
}
return MyClass;
}());
let x = new MyClass();
console.log(x.take())
希望这对你有帮助。
英文:
The issue is that MyClass.prototype.take
is an arrow function, but arrow functions don't have their own this
(see MDN), thus this
is the default window
and this._obj
is undefined
. You can either bind it yourself, or just make it a regular function like I did below.
Also, make sure to return a value from MyClass.prototype.take()
, or else you'll get undefined
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const MyClass = (function() {
function MyClass() {
this._obj = {
1: 'dfvdfvd'
};
}
function get() {
return this._obj[1];
}
MyClass.prototype.take = function() {
return get.call(this);
}
return MyClass;
}());
let x = new MyClass();
console.log(x.take())
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论