对象的创建方法
1.var obj = {} plainObject 对象字面量/对象直接量
2.构造函数
1) 系统自带的构造函数 new Object()
2) 自定义
1.系统自带的构造函数 new Object()
var obj = new Object();
obj.name = 'abc';
obj.say = function(){
console.log('mmmm');
}
2.自定义
//构造函数内部原理
//1.在函数体最前面隐式的加上this = {}
//2.执行this.xxx = xxx;
//3.隐式的返回this
function Person(color){
//var this = {};
this.name = "xxx";
this.height = 180;
this.color = color;
//return this;
}
例1:
var str = "abcd";
str.length = 2;
//当执行str.length = 2时,其实经历了一个这样的过程:
//1.new String('abcd').length = 2;
//2.delete length;
console.log(str); //abcd
console.log(str.length); //4
例2:
var str = "abc";
str += 1;
var test = typeof(str);
if(test.length == 6){
test.sign = "typeof的返回结果可能为String";
//同样也是经历了
//1.new String('string').sign = "typeof的返回结果可能为String";
//2.delete sign;
}
console.log(test.sign); //undefined
例3:
function Person (name,age,sex){
var a = 0;
this.name = name;
this.age = age;
this.sex = sex;
function sss(){
a ++ ;
document.write(a);
}
this.say = sss;
}
var oPerson = new Person();
oPerson.say(); //1
oPerson.say(); //2