Javascript-在对象方法中使用此
我有如下定义的javascript类:Javascript-在对象方法中使用此,javascript,oop,Javascript,Oop,我有如下定义的javascript类: function C_page() { this.errors = []; function void_log_str(L_message) { this.errors.push(L_message); } //and more code... } 问题是void\u log\u str作用域被用作这个。有什么办法可以代替它进入顶级吗 function C_page() { this.error
function C_page() {
this.errors = [];
function void_log_str(L_message) {
this.errors.push(L_message);
}
//and more code...
}
问题是void\u log\u str作用域被用作这个。有什么办法可以代替它进入顶级吗
function C_page() {
this.errors = [];
var that = this;
function void_log_str(L_message) {
that.errors.push(L_message);
}
//and more code...
}
我会这样做。你可以使用范围界定
var_this=这个;然后参考函数体中的_this。
或者您可以将函数绑定到该函数,例如,如果您的浏览器没有该函数,则使用function.prototype.bind或polyfill,您可以使用或每次调用函数时,选择希望该函数具有的值
。。。或者你可以用它来强制这种价值,它的好处是你在定义中这样做,而不是在调用中这样做
function C_page() {
this.errors = [];
var void_log_str = function(L_message) {
this.errors.push(L_message);
}.bind(this);
void_log_str("value of l message");
//and more code...
}
。。。或者您可以使用var=this方法
function C_page() {
var that = this;
this.errors = [];
function void_log_str(L_message) {
that.errors.push(L_message);
}
void_log_str("value of l message");
//and more code...
}
这将有助于:
function C_page() {
var context = this;
this.errors = [];
function void_log_str(L_message) {
context.errors.push(L_message);
}
//and more code...
}
不要使用根据调用函数的方式而变化的变量,而是使用范围中直接引用数组的变量:
function C_page() {
var errors = this.errors = [];
function void_log_str(L_message) {
errors.push(L_message);
}
//and more code...
}
您还可以使用bind:
有关处理此问题的更多方法,请参见。如何以及在何处调用它?
function C_page() {
var errors = this.errors = [];
function void_log_str(L_message) {
errors.push(L_message);
}
//and more code...
}
function C_page() {
this.errors = [];
var int_log_str = Array.prototype.push.bind(this.errors);
//and more code...
}