引用类内的变量..当“;这个"不起作用,因为我们处于函数中

Referring to a variable inside a class... when "this." does not work because we are in a function

本文关键字:我们 因为 于函数 函数 quot 变量 引用 这个 不起作用      更新时间:2023-09-26

假设有一个类机器人。

存在变量hand lefthandhand righthandleg leftlegleg rightlegleghand类包含int lengthint width

this.lefthand.length = 100;
this.leftleg.length = 200;
function switch_length () {
this.lefthand.length = 300; //This is wrong. So what can I do instead to refer to lefthand??
this.leftleg.length = 400; //This is wrong. So what can I do instead to refer to leftleg??
}
this.button.addEventlistener ( ... switch_length())

在Javascript中,您可以定义被调用函数的上下文。我更擅长用例子来解释这一点,所以它是这样的:

var something = {
    'foobar': 'var 1 value',
    'foo': function () {
        alert(this.var1);
    }
}
var something_else = {
    'foobar': 'some completely other value'
}
function bar () {
    alert(this.foobar);
}
something.foo(); //alerts 'var 1 value'
bar(); //produces an error
bar.call(something); //alerts 'var 1 value'
bar.call(something_else); //alerts 'some completely other value'

function.call(context, [arg1, [arg2, [...]]]);

如果这已经回答了你的问题,请务必接受我的回答。

编辑:下面是的另一个例子

function create () {
    return  {
        'hand': {
            'length': 100
        },
        'leg': {
            'length': 100
        }
    }
}
function set_length(hand, leg) {
    this.hand.length = hand;
    this.leg.length = leg;
}
var left = create(),
    right = create();
set_length.call(left, 200, 300);
set_length.call(right, 50, 150);
相关文章: