Showing posts with label Variable. Show all posts
Showing posts with label Variable. Show all posts

Wednesday, February 13, 2008

Ruby class variable, class attribute(class instance variable), class constant tips


class Class_Attribute
@var = 1 #class attribute or class instance variable

def initialize
@var = 2 #instance attribute
end

def report
@var # instance attribute, not the class attribute
end

def Class_Attribute.report
@var # class attribute
end
end

class Child_A < Class_Attribute
@var = 3
end

puts Class_Attribute.report #=> 1
puts Class_Attribute.new.report #=> 2
puts Child_A.report #=> 3
puts Child_A.new.report #=> 2

class Class_Constant
VAR = [ 'a' ]
VAR2 = [ 'b' ]

def self.report
VAR2[0]
end
end

class Child_C < Class_Constant
VAR2 = [ 'c' ]
end

puts Class_Constant::VAR[0] #=> 'a'
puts Class_Constant::VAR2[0] #=> 'b'
puts Class_Constant.report #=> 'b'
puts Child_C::VAR2[0] #=> 'c'
puts Child_C.report #=> 'b'
puts Child_C::VAR[0] #=> 'a'

from David A. Black:

@@avar = 1
class A
@@avar = "hello"
end
puts @@avar # => hello

A.class_eval { puts @@avar } # => hello

If you’re just looking to store some data in a variable which is unique to your class, but accessible from instances or externally, why not just use instance variables?

class A
@foo = "bar"
class << self; attr_reader :foo; end
end
nil
A.foo #=> "bar"

references:http://www.oreillynet.com/ruby/blog/2007/01/nubygems_dont_use_class_variab_1.html

Sunday, January 27, 2008

javascript中相同命名空间下函数名和变量名冲突


<script type="text/javascript" charset="utf-8">
function test() {
alert(arguments.callee);
}
var test = 'xyz';
alert(test); // 'xyz'
test(); //test is not a function [Break on this error] test();
</script>

函数名其实也是一个变量名,所以是会发生冲突的。

Thursday, January 10, 2008

ActionScript 变量作用域说明

与 C++ 和 Java 中的变量不同的是,ActionScript 变量没有块级作用域。代码块是指左大括号 ({) 与右大括号 (}) 之间的任意一组语句。在某些编程语言(如 C++ 和 Java)中,在代码块内部声明的变量在代码块外部不可用。对于作用域的这一限制称为块级作用域,ActionScript 中不存在这样的限制,如果您在某个代码块中声明一个变量,那么,该变量不仅在该代码块中可用,而且还在该代码块所属函数的其它任何部分都可用。例如,下面的函数包含在不同的块作用域中定义的变量。所有的变量均在整个函数中可用。
有趣的是,如果缺乏块级作用域,那么,只要在函数结束之前对变量进行声明,就可以在声
明变量之前读写它。这是由于存在一种名为“提升”的方法,该方法表示编译器会将所有的
变量声明移到函数的顶部。例如,下面的代码会进行编译,即使 num 变量的初始 trace() 函
数发生在声明 num 变量之前也是如此。
trace(num); // NaN
var num:Number = 10;
trace(num); // 10
但是,编译器将不会提升任何赋值语句。这就说明了为什么 num 的初始 trace() 会生成 NaN(而非某个数字), NaN 是 Number 数据类型变量的默认值。这意味着您甚至可以在声明变量之前为变量赋值,如下面的示例所示:
num = 5;
trace(num); // 5
var num:Number = 10;
trace(num); // 10


function blockTest(testArray:Array) {
var numElements:int=testArray.length;
if (numElements > 0) {
var elemStr:String="Element #";
for (var i:int=0; i < numElements; i++) {
var valueStr:String=i + ": " + testArray[i];
trace(elemStr + valueStr);
}
trace(elemStr,valueStr,i);// 仍定义了所有变量
}
trace(elemStr,valueStr,i);// 如果 numElements > 0,则会定义所有变量
}
blockTest(["Earth","Moon","Sun"]);

Monday, January 07, 2008

WARNING DON’T LEAVE OUT THE DOT WHEN IT’S NEEDED [R4R page 186]

In one situation, you must use the full object-dot-message notation, even if you’re sending the message to the current self: when the method is a setter method—a method whose name ends with an equal sign. You have to do self.venue = "Town Hall" rather than venue = "Town Hall", if you want to call the method venue=. The reason is that Ruby always interprets the sequence: bareword = value as an assignment to a local variable. To call the method venue= on the current object, you need to include the explicit self. Otherwise, you’ll end up with a variable called venue and no call to the setter method.

Monday, October 15, 2007

Function() constructor of JavaScript

There are a few points that are important to understand about the Function() constructor:

The Function() constructor allows JavaScript code to be dynamically created and compiled at runtime. It is like the global eval() function (see Part III) in this way.

The Function() constructor parses the function body and creates a new function object each time it is called. If the call to the constructor appears within a loop or within a frequently called function, this process can be inefficient. By contrast, a function literal or nested function that appears within a loop or function is not recompiled each time it is encountered. Nor is a different function object created each time a function literal is encountered. (Although, as noted earlier, a new closure may be required to capture differences in the lexical scope in which the function is defined.)

A last, very important point about the Function() constructor is that the functions it creates do not use lexical scoping; instead, they are always compiled as if they were top-level functions, as the following code demonstrates:


var y = "global";
function constructFunction() {
var y = "local";
return new Function("return y"); // Does not capture the local scope!
}

// This line displays "global" because the function returned by the
// Function() constructor does not use the local scope. Had a function
// literal been used instead, this line would have displayed "local".
alert(constructFunction()()); // Displays "global"

Saturday, July 14, 2007

static variable of Javascript


<script type="text/javascript" charset="utf-8">
function doc (argument) {
document.write(argument);
document.write("<br />\n");
}

// Define a static variable to hold the running static_var over all calls
// Can't claim static variable with key "var", this is function Object's properties
function doSome (a) {
doSome.static_var ++;
return a + doSome.static_var;
}
doc(typeof doSome); //function Object
doSome.static_var = 0; // var doSome.static_var = 0 will error.
doc(doSome(1)); //2
doc(doSome(1)); //3
doc(doSome(1)); //4
doSome.static_var = 0;
doc(doSome(1)); //2
for (i in doSome)
{
doc(i);
/*static_var
prototype
bind
bindAsEventListener*/
}
</script>

Class Properties
In addition to instance properties and properties of prototypes, JavaScript allows you to define class properties (also known as static properties), properties of the type rather than of a particular object instance. An example of a class property is Number.MAX_VALUE. This property is a type-wide constant, and therefore is more logically located in the class (constructor) rather than individual Number objects. But how are class properties implemented?
Because constructors are functions and functions are objects, you can add properties to constructors. Class properties are added this way. Though technically doing so adds an instance property to a type’s constructor, we’ll still call it a class variable. Continuing our example,

doSome.static_var = 0;

defines a class property of the doSome object by adding an instance variable to the constructor. It is important to remember that static properties exist in only one place, as members of constructors. They are therefore accessed through the constructor rather than an instance of the object.
As previously explained, static properties typically hold data or code that does not depend on the contents of any particular instance. The toLowerCase() method of the String object could not be a static method because the string it returns depends on the object on which it was invoked. On the other hand, the PI property of the Math object (Math.PI) and the parse() method of the String object (String.parse()) are perfect candidates, because they do not depend on the value of any particular instance. You can see from the way they are accessed that they are, in fact, static properties. The isMetallic property we just defined is accessed similarly, as doSome.static_var.

Monday, July 02, 2007

Ruby attr_accessor使用


class Name
attr_accessor :name

def initialize
@name = ""
p @name.object_id
puts "\n"
end

def set_name(input_name)
name = input_name
self.name = input_name
end

def gets_name
p @name
p @name.object_id
p self.name
p self.name.object_id
end
end

a = Name.new
a.set_name('test')
a.gets_name
p a.name
p a.name.object_id

# >> 1647780
# >>
# >> "test"
# >> 1647790
# >> "test"
# >> 1647790
# >> "test"
# >> 1647790

puts "\n"
a.name = 'text'
a.gets_name
p a.name
p a.name.object_id

# >>
# >> "text"
# >> 1647680
# >> "text"
# >> 1647680
# >> "text"
# >> 1647680


self.name中的self是指当前的实例对象a,而self.name这个方法返回的则是对象a里的实例变量@name的值。
另:R4R第7章内容是关于ruby self的使用,说得非常详细,不同的作用域self代表的是不同的对象。
The default object (self) and scope In this chapter
■ The role of the current or default object, self
■ Scoping rules for variables and constants
■ Method access rules

Sunday, May 27, 2007

在MYSQL使用用户变量

可以清空MySQL用户变量以记录结果,不必将它们保存到客户端的临时变量中。(参见 9.3节,“用户变量”.)。

例如,要找出价格最高或最低的物品的,其方法是:

mysql> SELECT @min_price:=MIN(price),@max_price:=MAX(price) FROM shop;
mysql> SELECT * FROM shop WHERE price=@min_price OR price=@max_price;

Sunday, March 25, 2007

variable variables

将某变量值作为变量名时需要注意在结合array使用时的一个问题:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example address.


<?php
function global_ref()
{
//在function中用global,static引入的变量其实是对此变量建立了一个引用reference,
//在function执行完之后会对应变量的值不会丢失。
global $obj;
var_dump($obj);
echo "<br/>";
$obj = &new stdclass;
}
global_ref();
global_ref();
?>

<br/>

<?php
function global_noref()
{
global $obj;
var_dump($obj);
echo "<br/>";
if(!isset($obj))
{
$obj = new stdclass;
}
else
{
echo "has set variable: \$obj. <br/>";
}
}
global_noref();
global_noref();
?>
A similar behaviour applies to the static statement. References are not stored statically:

<?php
function static_ref()
{
static $sta;
var_dump($sta);
if(!isset($sta))
{
$sta = &new stdclass;
}
$sta->num++;
}
static_ref();
static_ref();
static_ref();
?>

<?php
function static_noref()
{
static $sta;
var_dump($sta);
echo "<br>";
if(!isset($sta))
{
$sta = new stdclass;
}
$sta->num++;
}
static_noref();
static_noref();
static_noref();
?>

Using the global keyword inside a function to define a variable is essentially the same as passing the variable by reference as a parameter:

somefunction(){
global $var;
}

is the same as:

somefunction(& $a) {

}

The advantage to using the keyword is if you have a long list of variables needed by the function - you dont have to pass them every time you call the function.

Thursday, February 22, 2007

Functions and variables conllision of names

Name Functions Well When naming functions and variables, you need to be a little careful. Because functions and variables share the same namespace, you shouldn’t be declaring variables and functions with the same name. It might be a good idea to precede function names with “func” or some other string or letter of your own choosing. So, using such a scheme, if we had a variable named hello and wanted to define a function also called hello, we would use funcHello.
Note
Some developers prefer different casing to distinguish between variables and functions, but this may not be obvious enough. The choice is a matter of style and we leave it open for readers to decide for themselves.
Besides the obvious collision of names, very subtle bugs may slip in when we have similar names, particularly when you consider that functions are created when the document is parsed, while variables are created when the script is run. Notice in the following script how there is a variable as well as a function called x.
var x = 5;
function x()
{
alert("I'm a function!");
}
alert(typeof x);
You might expect the alert to show x to be a function or, more appropriately, an object because it appears to be defined second. However, as you can see here, it is a number:

The output makes sense if you consider when the function and variables are actually created. The function is created as the script is parsed, while the variable gets created as the script runs. While this was a contrived example, it illustrates the importance of understanding how things are created in JavaScript.