在我自己的数组方法中使用array.push()会产生错误(JavaScript)? [英] Using array.push() inside my own array method gives error (JavaScript)?
本文介绍了在我自己的数组方法中使用array.push()会产生错误(JavaScript)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码示例:
function s () {
this.func = [];
this.func.addF = function (str) {
this.func.push(str);
}
}
当我创建该对象的实例时:
When I create an Instance of that object:
var a = new s ();
a.func.addF ("hello");
我收到错误消息:未捕获的TypeError:无法读取未定义的属性'push'。
我可以理解 this.func
在那时是未定义的,但我应该怎么做使这项工作。请帮忙。
I can understand that this.func
is undefined at that point, but what should I do to make this work. Pls help.
推荐答案
这个
有问题。在javascript中,此
指向绑定上下文或用于调用函数调用的内容。这个值取决于函数的调用方式。
There is a problem with this
. In javascript, this
point to the binding context or what was used to invoke the function call. The value of this is determined by how a function is called.
function s () {
var self = this;
self.func = [];
self.func.addF = function (str) {
self.func.push(str);
}
}
var a = new s ();
a.func.addF("hello"); // Display 'hello'
这篇关于在我自己的数组方法中使用array.push()会产生错误(JavaScript)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文