这两种写法到底哪种好??发现现在好多都是写成第一种形式。为什么?
第一种:<script type="text/javascript">
var obj=
{
bl:"haohao",
ff:function()
{
alert(obj.bl);
}
}; obj.ff();
</script>
第二种:<script type="text/javascript">
var bl="haohao"; function ff()
{
alert(bl);
} ff();
</script>
第一种:<script type="text/javascript">
var obj=
{
bl:"haohao",
ff:function()
{
alert(obj.bl);
}
}; obj.ff();
</script>
第二种:<script type="text/javascript">
var bl="haohao"; function ff()
{
alert(bl);
} ff();
</script>
很支持这样的写法。
第二种是js的一般用法
明显的好处就是全局变量少了
第二种是js的一般用法
我宁愿把第一种对象组织形式叫json格式,是一种轻巧且清晰的结构。
var obj=
{
bl:"haohao",
ff:function()
{
alert(obj.bl);
}
}; obj.ff();
相当于
var obj = new Object;
obj.b1 = "haohao"
obj.ff = function(){alert(obj.bl)};
obj.ff();而你第二种所有变量都是全局的变量。一般javascript脚本能不用全局变量就不用。效率是个问题,变量冲突,污染也是个问题
这里有篇文章可以参考
http://www.cnblogs.com/justinw/archive/2010/03/17/1688113.html#avoidglobal
也可以当作map使用,可用for in 得到自定义的属性
for (var k in o) { alert(k + '=' + o[k]); }
return function () { };
}据我所知上面应该才是闭包把。
能不能不用foreach循环,写成 简单的for循环呢?
我知道没有foreach,只不过这种形式跟foreach差不多。我想要写成 for(var i=0;i<5;i++) 这种形式
bl:"haohao",//这是给名字空间中添加方法,或常量。
...
}; function funName() { //这个叫做函数,或构造函数,当用var o = new funName()它是o的原型对象
this.shuxing
}在js函数就是一个闭包,但真正的闭包是这么写:
function funName() {
return function() {return true;}
}下边是一个例子,原文地址在:http://blog.sina.com.cn/s/blog_680a81e10100josc.html
/* Bounce.js: A floating window to free.
* Version: 1.0.
*
* This module defines a single global symbol named "Bounce".
*
* Copyright (C) By Mr.lonely
* e-Mail:[email protected]
* [email protected]
*/ try {
var Bounce; if(!Bounce) Bounce = {};
else if(typeof Bounce != "object") throw new Error("\"Bounce\" already exists, but the type it is not an object."); (function() {
var _x = 0, _y = 0, _w = 200, _h = 200;
var _dx = 3; _dy = 3;
var _interval = 30;
var _win = null, _timer = null;
function _start() {
_x = (screen.width - _w) / 2;
_y = (screen.height - _h) / 2;
_win = window.open("javascript:\"<h1>BOUNCE!</h1>\"",
"",
"left=" + _x + ", top=" + _y + ", width=" + _w + ", height=" + _h + ", status=yes");
_timer = setInterval(_nextWin, _interval);
}
function _stop() {
clearInterval(_timer);
if(!_win.closed) _win.close();
}
function _nextWin() {
if(_win.closed) {
clearInterval(_timer);
return;
}
if((_x + _dx > (screen.availWidth - _w)) || (_x + _dx < 0)) _dx = -_dx;
if((_y + _dy > (screen.availHeight - _h)) || (_y + _dy < 0)) _dy = -_dy;
_x += _dx;
_y += _dy;
_win.moveTo(_x, _y);
_win.defaultStatus = _x + "," + _y;
}
Bounce.start = _start;
Bounce.stop = _stop;
Bounce.version = function() {return "1.0";}
})()
} catch(e) {
alert(e.message);
}