日期:2014-05-16 浏览次数:20487 次
/* Anim class. */
var Anim = function() {
...
};
Anim.prototype.start = function() {
...
};
Anim.prototype.stop = function() {
...
};
/* Usage. */
var myAnim = new Anim();
myAnim.start();
...
myAnim.stop();
/* Anim class, with a slightly different syntax for declaring methods. */
var Anim = function() {
...
};
Anim.prototype = {
start: function() {
...
},
stop: function() {
...
}
};
<html>
<head>
<title>String Example</title>
<script type="text/javascript">
//在javascript中,函数都最好的对象
//函数的大部分概念和C++没有什么区别。值得注意的是匿名函数
//示例如下:
/* An anonymous function, executed immediately. */
(function(){
var foo = 10;
var bar = 2;
alert(foo * bar);
})();
//这个函数的定义和执行并没有分配给任何变量。最后的()执行了这个函数。
//他们是空的,但是并不是这种情况
/* An anonymous function with arguments. */
(function(foo, bar){
alert(foo * bar);
})(10, 2);
//下例同第一个例子等价。不过将值给了一个内在的变量
/* An anonymous function that returns a value. */
var baz = (function(foo, bar){
return foo * bar;
})(10, 2);
alert(baz);
//匿名函数最有趣的应用时建立闭包。
//闭包是一个受保护的变量空间,这就是说闭包函数可以在他们所定义的任意地方执行。不受函数体影响
/* An anonymous function used as a closure. */
var baz;
(function(){
var foo = 10;
var bar = 2;
baz = function(){
return foo * bar;
};
})();
baz(); // baz can access foo and bar, even though it is executed outside of the class
</script>
</head>
<body>
<!-- Nothing in the body -->
//在javascript中,函数都最好的对象
//函数的大部分概念和C++没有什么区别。值得注意的是匿名函数
//示例如下:
/* An anonymous function, executed immediately. */
(function(){
var foo = 10;
var bar = 2;
alert(foo * bar);
})();
//这个函数的定义和执行并没有分配给任何变量。最后的()执行了这个函数。
//他们是空的,但是并不是这种情况
/* An anonymous function with arguments. */
(function(foo, bar){
alert(foo * bar);
})(10, 2);
//下例同第一个例子等价。不过将值给了一个内在的变量
/* An anonymous function that returns a value. */
var baz = (function(foo, bar){
return foo * bar;
})(10, 2);
alert(baz);
//匿名函数最有趣的应用时建立闭包。
//闭包是一个受保护的变量空间,这就是说闭包函数可以在他们所定义的任意地方执行。不受函数体影响
/* An anonymous function used as a closure. */
var baz;
(function(){
var foo = 10;
var bar = 2;
baz = function(){
return foo * bar;
};
})();
baz(); // baz can access foo and bar, even though it is executed outside of the class
</body>
</html>
/* Add a method to the Function object that can be used to declare methods. */
Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
};
/* Anim class, with methods created using a convenience method. */
var Anim = function() {
...
};
Anim.method('start', function() {
...
})