命名空间问题
访问:
很麻烦
var jicheng = org.department1.jicheng;
jicheng.name;
通过立即执行函数解决命名空间问题
好处:形成闭包,私有化变量防止污染全局变量
var name ="bcd";
var init = (function(){
var name = "abc";
function callName(){
console.log(name);
}
return function(){
callName();
}
}())
要连续使用方法时返回this
var deng = {
smoke :function(){
console.log("smoke");
return this;
},
drink: function(){
console.log("drink");
return this;
},
perm : function(){
console.log("perm");
return this;
}
}
deng.smoke().drink().perm();
obj.name -----> obj[‘name’]
var deng = {
wife1 : {name :"1sfdjn"},
wife2 : {name :"2sfdjn"},
wife3 : {name :"3sfdjn"},
wife4 : {name :"4sfdjn"},
sayWife : function(num){
return this['wife'+ num];
}
}
对象枚举
var obj = {
name:'13',
age:123,
sex:'male',
heght:180,
weight:75,
__proto__:{
lastName:"deng"
}
}
有两种方式使用 in 操作符:
- 单独使用
在单独使用时, in 操作符会在通过对象能够访问给定属性时返回 true,无论该属性存在于实例中还是原型中。
//in
'name' in obj;
- for-in 循环中使用。可以用作对象枚举
alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
//for in
//hasOwnProperty()
for (var prop in obj){
if(obj.hasOwnProperty(prop)){ //排除原型属性(自己手动设定的)
console.log(prop+" "+typeof(prop)+" "+obj[prop]);
//不能写为obj.prop 因为prop是string
}
}
补充:
-
hasOwnProperty():使用 hasOwnProperty()方法可以检测一个属性是存在于实例中,还是存在于原型中。只在给定属性存在于对象实例中时,才会返回 true。
-
isPrototypeOf():检测一个对象是否是另一个对象的原型。或者说一个对象是否被包含在另一个对象的原型链中
-
hasOwnProperty和in配合使用来判断属性是否是在原型上
function hasPrototypeProperty(object, name){
return !object.hasOwnProperty(name) && (name in object);
}
由于 in 操作符只要通过对象能够访问到属性就返回 true, hasOwnProperty()只在属性存在于实例中时才返回 true,因此只要 in 操作符返回 true 而 hasOwnProperty()返回 false,就可以确定属性是原型中的属性。
instanceof
A instanceof B : A是不是B构造出来的
表示的意义是:A的对象上的原型连上 有没有 B的原型
区别对象的三种方法(区别数组和对象)
- constructor方法
obj.constructor
[].constructor - instanceof 方法
[] instanceof Array //true
obj instanceof Array //false
- toString方法
Object.prototype.toString.call([])
Object.prototype.toString.call(123)