所以,我看到了几个例子,这应该有效。但显然,我错过了一些东西,因为它没有。:/
有人可以向我解释我在这里做错了什么吗?:)
function Code (b) {
this.b = b
this.arr = []
}
Code.prototype.add = (v) => {
console.log(this.b)
this.arr.forEach(element => {
console.log(element)
});
this.arr.push(v)
}
var c = new Code('bla')
console.log(c.add('asdf'))
所以这会引发一个错误:
this.arr.forEach(element => {
^
TypeError: Cannot read property 'forEach' of undefined
显然,我在这里做错了。但我不知道是什么。
谢谢!格格利。
function Code (b) {
this.b = b
this.arr = []
}
Code.prototype.add =function(v){
console.log(this.b)
this.arr.forEach(function(element){
console.log(element)
});
this.arr.push(v)
console.log(this.arr)
}
var c = new Code('bla')
console.log(c.add('asdf'))
您应该使用function()
, instaed of () =>
arrow fucntion,因为箭头函数的this
工作方式不同。
this
箭头函数只指this
存在于外部作用域中的那个。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句