我可以在JavaScript类上创建私有成员,如下所示:
function Class(_foo, _bar) {
var foo = _foo, // private, yay
bar = _bar; // also private, also yay
}
Run Code Online (Sandbox Code Playgroud)
如何为此类实现通用的setter/getter方法?我想一种方法是使用eval
:
function Class(_foo, _bar) {
var foo = _foo,
bar = _bar;
this.get = function(property) {
return eval(property);
};
this.set = function(property, value) {
eval(property + " = " + value);
};
}
Run Code Online (Sandbox Code Playgroud)
但是,这个解决方案很难看.另一种方法是创建一个private
对象,然后访问该属性:
function Class(foo, bar) {
var private = {
foo: foo,
bar: bar
};
this.get = function(property) {
return private[property];
};
this.set …
Run Code Online (Sandbox Code Playgroud) 我是Lua的新手,所以(很自然地)我遇到了我试图编程的第一件事.我正在使用Corona Developer软件包提供的示例脚本.这是我试图调用的函数的简化版本(删除了无关材料):
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
Run Code Online (Sandbox Code Playgroud)
如果我尝试像这样调用该函数:
local test = slideView.new( myImages )
test.jumpToImage(2)
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
尝试将数字与零比较
在第225行.似乎"num"没有被传递到函数中.为什么是这样?
def findDistance():
first_coord = raw_input("Enter first coordinate set (format x, y): ").split(",")
second_coord = raw_input("Enter second coordinate set (format x, y): ").split(",")
x1 = float(first_coord[0])
x2 = float(second_coord[0])
y1 = float(first_coord[1])
y2 = float(first_coord[1])
print math.sqrt(float(((x2 - x1) * (x2 - x1))) + float(((y2 - y1) * (y2 - y1))))
Run Code Online (Sandbox Code Playgroud)
放入系列(10,12),(12,10)给出2.0,当实际距离(有点圆)是2.82842
.看起来Python正在铺设我的号码.为什么以及如何发生这种情况?
我想不出一种方法可以解释我所追求的东西,而不是我在标题中所做的,所以我会重复一遍.从对象内调用的匿名函数是否可以访问该对象的范围?以下代码块应该解释我正在尝试做的比我更好:
function myObj(testFunc) {
this.testFunc = testFunc;
this.Foo = function Foo(test) {
this.test = test;
this.saySomething = function(text) {
alert(text);
};
};
var Foo = this.Foo;
this.testFunc.apply(this);
}
var test = new myObj(function() {
var test = new Foo();
test.saySomething("Hello world");
});
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到一个错误:"没有定义Foo." Foo
当我调用匿名函数时,如何确保定义?这是一个进一步实验的jsFiddle.
编辑:我知道将这行添加var Foo = this.Foo;
到我传入我的实例的匿名函数中myObj
会使这个工作.但是,我想避免在匿名函数中公开变量 - 我还有其他选择吗?
刚刚注意到JS中自动类型转换的一个特殊副作用:
if (false || false) {
}
Run Code Online (Sandbox Code Playgroud)
是相同的:
if (false + false) {
}
Run Code Online (Sandbox Code Playgroud)
而且两者(false || true)
并(false + true)
会返回相同的结果(真).
为什么+
在这种情况下看不到更多用途?是否有一个可靠的原因(除了可能令人困惑的代码)我们不应该用+
它代替||
?
我想可能会因额外的演员而受到性能影响,但是嘿 - 我们正在拯救一个角色!是的,一个微优化取代另一个!