渡一—— 12-2 繼承模式,名稱空間,物件列舉(下)
阿新 • • 發佈:2021-09-22
名稱空間
管理變數,防止汙染全域性,適用於模組化開發
物件方法
var org = { department1 : { jicheng : { name : "abc", age : 123 }, xuming : { } }, department2 : { zhangsan : { }, lisi : { } } } // org.department1.jicheng.name varjicheng = org.department1.jicheng jicheng.name
2,閉包 模組化開發
// 現在用工具類webpack,groud
var name = "bbb" var init = (function(){ var name = "abc"; function callName(){ console.log(name); } return function(){ callName(); } }()) init() //abc
var initDeng = (function(){var name = 123; function callName(){ console.log(name); } return function(){ callName(); } }()) initDeng();
鏈式呼叫.css().html().css()
var deng = { smoke : function (){ console.log("smoking,...xuan cool!!!"); return this; }, drink : function(){ console.log("drinking...,ye cool!"); return this; }, perm : function(){ console.log("preming...,cool!"); return this; } } deng.smoke(); deng.drink(); deng.prem(); deng.smoke().drink().prem().smoke();
屬性的表示方法
系統預設是obj['name'] var obj = { name : "abc" } obj.name //abc obj['name'] //abc obj.name --> obj['name'] var deng = { wife1 : {name : "xiaoliu"}, wife2 : {name : "xiaozhang"}, wife3 : {name : "xiaomeng"}, wife4 : {name : "xiaowang"}, sayWife : function(num){ /*switch(num){ case 1: return this.wife1; case 2: return this.wife2; }*/ return this['wife'+num] } }
物件的列舉
for in
for in 上的方法
1.hasOwnProperty
2.in
3.instanceof
var arr = [1,3,3,4,5,6,6,7,7]; //遍歷 列舉 enumeration for(var i=0;i<arr.length;i++){ console.log(arr[i]); } //遍歷物件 var obj = { name : "aaa", age : 123, sex : "male", height : 180, wight : 75, } for(var prop in obj){ console.log(prop + '*' + typeof(prop)); //name*string age*string... conso.log(obj.prop) //-->obj['prop'] 列印5個undefined conso.log(obj[prop]) //"aaa" 123... } var obj1 = { a : 123, b : 234, c : 345, } for(var prop in obj1){ console.log(obj.prop++) }
hasOwnProperty 排除原型上的屬性
作用:不想顯示__proto__上的方法
var obj = { name : "aaa", age : 123, sex : "male", height : 180, wight : 75, __proto__:{ lastName:"deng" } } for(var prop in obj){ if(obj.hasOwnProperty(prop)){ conso.log(obj[prop]) //不顯示lastName } }
in檢視屬性是不是物件的,包括自己的和原型父級的屬性(沒什麼用)
'height' in obj //true
'lastName' in obj //true
instanceof
A instanceof B
物件 是不是 B建構函式構造出來的
看A物件的原型鏈上 有沒有 B的原型
function Person(){} var person = new Person(); person instanceof Person //true person instanceof object //true
[] instanceof Array //true [] instanceof object //true typeof([]) //object typeof({}) //object
判斷是陣列或是物件
//1 var obj={}; obj.constructor //function Object(); [].constructor //function Array(); //2 [].instanceof Array //true obj instanceof Array //false //3 toString [1,2,3].toString -->Number.toString()-->'1,2,3' Object.prototype.toString.call([]) -->Object.toString()-->'[object Array]' Object.prototype.toString.call(123) '[object Number]'