sam*_*oul 1 javascript private class
我有一个简单的Javascript类,我正在尝试制作它,直到我遇到一个似乎不应该发生的问题.我有以下课程:
function circle(paper) {
var x = null;
var y = null;
var r = null;
var x1 = null;
var y1 = null;
var R = 0;
this.G = 0;
this.B = 0;
this.lineSize = 1;
this.paper = paper;
var that = this;
this.set = function(x,y,r){
that.x = x;
that.y = y;
that.r = r;
}
this.colorOut = function(){
console.log("R: "+that.R+" G: "+this.G+" B: "+this.B);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,无论我做什么,R都会变得不确定,但是如果我这样做var R = null;并且在集合中我会that.R = 0;突然确定它.然而,根据我在crockford网站上发现的许多SO帖子链接到这些问题,看起来他正在做我正在做的事情并且它正在发挥作用.如下面的代码所示:
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
return dec() ? that.member : null;
};
}
Run Code Online (Sandbox Code Playgroud)
那么,有什么我在这里不理解,或者是误解?我是JS中的类如何工作的新手,我更多地使用Java/C++类.无论如何,如果你需要更多的信息,请问!谢谢很多!
两者之间有很大的不同
var R;
Run Code Online (Sandbox Code Playgroud)
和
this.R = something;
Run Code Online (Sandbox Code Playgroud)
第一个是局部变量声明.它不会向任何对象添加属性.变量将在与对象属性关联的任何函数内可见,因为函数是在该构造函数内创建的.变量"R"是在实例化函数时形成的闭包的一部分.
第二个在正在构建的对象上建立一个名为"R"的属性.
编辑 - 进一步澄清:
this.colorOut = function(){
console.log("R: "+that.R+" G: "+this.G+" B: "+this.B);
}
Run Code Online (Sandbox Code Playgroud)
在该函数中,您将"R"称为构造对象的属性; 这that.R意味着什么.当你所有的都是那个var R;声明时,对象上没有这样的属性.但是有一个局部变量,所以你可以改变功能:
this.colorOut = function(){
console.log("R: " + R + " G: "+this.G+" B: "+this.B);
}
Run Code Online (Sandbox Code Playgroud)
并且你会看到局部变量"R"的值,无论它是什么.(如果你没有初始化它,那么它undefined无论如何都会.)
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |