您的位置:首页 > Web前端 > JavaScript

js 基础回顾

2013-11-21 14:28 239 查看
1.循环Object的所有属性

var config = {verbose :false, filepaths :[], doSomthing :function(){}};
for(var i in config){
if(config.hasOwnProperty(i)){ // 语法点
alert(i);
}
}
2.方法的参数为array类型,在方法内部对参数合法性的检验

function setLinters(linters){
if (!(linters instanceof Array) || linters.length === 0) { // 语法点
return false;
}else{
return linters.length;
}
}
setLinters([]); // false
setLinters([1,'5']); // 2
setLinters(21); // false


另,判断是否为数组
Object.prototype.toString.call(arr)==='[object Array]'


3.判断对象类型
/* 检测对象类型
* @param: obj {JavaScript Object}
* @param: type {String} 以大写开头的 JS 类型名
* @return: {Boolean}
*/
function is(obj, type)  {
return Object.prototype.toString.call(obj).slice(8, -1) === type;
}


4. 复制对象
/* 复制对象
* @param: obj {JavaScript Object} 原始对象
* @param: isDeep {Boolean} 是否为深拷贝
* @return: {JavaScript Object} 返回一个新的对象
*/
function copy(obj, isDeep) {
var ret = obj.slice ? [] : {}, p;
// 配合 is 函数使用
if(!isDeep && is(obj, 'Array')) return obj.slice();
for(p in obj) {
var prop = obj[p];
if(!obj.hasOwnProperty(p)) continue;
if(is(prop, 'Object') || is(prop, 'Array')) {
ret[p] = copy(prop, isDeep);
} else {
ret[p] = prop;
}
}
return ret;
}


4.自执行函数的用法,以及在内层应用外层对象
var LintRoller = {
version : '2.3',
name : 'ouc wy',
innerFun : function(){
var me = this;         // 语法点1
(function(){           // 语法点2
alert(me.name);    // 对外层的引用 'ouc wy'
alert(this.name);  // 当前对象作用域 ''
alert(this.other); // undefined
})();
}
};
LintRoller.innerFun();
// 此处有一点疑问:第8、9行为什么不报引用错误?


var LintRoller = {
version : '2.3',
name : 'ouc wy',
innerFun : function(){
var me = this;         // 语法点1
(function(){           // 语法点2
alert(me.name);    // 对外层的引用 'ouc wy'
alert(this.name);  // 'hello,word'
alert(this.other); // undefined
})();
}
};
var name = 'hello,word';
LintRoller.innerFun();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息