gpt4 book ai didi

javascript - 在函数中定义变量时何时使用 `this`

转载 作者:行者123 更新时间:2023-11-30 06:26:02 25 4
gpt4 key购买 nike

根据我目前所读的内容,我们可以使用函数在 javascript 中创建具有“私有(private)”/“公共(public)”成员的对象。一些东西:

function foo(param1) {
this.publicVar= param1;
privateVar = "can't touch this";

this.MC = function(){
var ret = privateVar + ", " + this.publicVar;
return ret;
};
}

当调用 var f = new foo("hammer time"); 时,我可以使用 f.publicVar & f.MC( ) ,但我无法触及 privateVar

正如您在此 jsbin 中看到的那样, 一切似乎都有效。

我不明白的是在这种情况下使用 this。使用 this.privateVar 将是未定义的,使用 publicVar 而不使用 this 将是未定义的。

这是一个更详细的示例:jsfiddle .
有 2 个选项来创建对象,并尊重地调用它们:

function Option1(aX,aY) {
var x,y;

x = aX || 0; // `||` serves as guard, in case parameters
y = aY || 0; // are not defined, initializes to 0;

this.toString = function() {
var retStr = "from Option 1: I am here: <br/>"+
"x: " + x + "<br/>" + // 1
"y: " + y + "<br/>" + // 1
"this.x: " + this.x + "<br/>" + // undefined
"this.y: " + this.y + "<br/>" + // undefined
"aX: " + aX + "<br/>" + // 1
"aY: " + aY ; // 1
return retStr;
};
// `this` is returned implicitly
}

// first has only toString() as "public" member
var first = new Option1(1,1);

问题一:
toString 中,xy 出现在 closure 中的 scope variables 中在 chrome 调试器中,但无法通过 this 访问。

function Option2(aX,aY) {
var x,y;

this.x = aX || 0;
this.y = aY || 0;

this.toString = function() {
var retStr = "from Option 2: I am here: <br/>"+
"x: " + x + "<br/>" + // undefined
"y: " + y + "<br/>" + // undefined
"this.x: " + this.x + "<br/>" + // 22
"this.y: " + this.y + "<br/>" + // 22
"aX: " + aX + "<br/>" + // 22
"aY: " + aY ; // 22
return retStr;
};

}

// second has x,y & toString() as "public" members
var second = new Option2(22,22);

问题二:
在这个 toString 中,x & y DO NOT 出现在 closure 中chrome 调试器中的 scope 变量,并且只能通过 this 访问。

我希望在 Option2 中能够访问 x,因为它将从外部函数继承它,但是没有 是不可能的这个

任何澄清将不胜感激。干杯。

最佳答案

在选项 1 中(我将只用一个变量来做例子)

function Option1(aX) {
var x; //defining x variable with a certain memory adress
x = aX || 0; //assigning to it a value

//in this case "this.x" doesn't exist

}

在选项 2 中:

function Option2(aX) {
var x;//defining x variable with a certain memory adress

this.x = aX || 0; //defining another variable with different memory address and
//assign to it the value of the passing parameter


//in this case this.x != x

}

互相学习,如有错误请指正

关于javascript - 在函数中定义变量时何时使用 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com