27、创建对象
①工厂模式批量创建对象 缺点:无法对象识别,即所有对象都是Object类型;方法内存空间浪费/封装不太完善
function sayName(){ //可以有效节省内存空间
console.log(this.name);
}
function createObject(name, age, gender){
var obj = {
name:name,
age:age,
gender:gender,
sayName: sayName, //将方法写在外面,可以有效节省内存空间
};
return obj; //或者直接返回对象
}
var o1 = createObject('zhangsan', 12, 'man');
var o2 = createObject('lisi', 15, 'woman');
var dog = createObject('erha', 4, 'man');
console.log(o1, o2, dog);
//通过实例找构造函数
console.log(o1.constructor); //Object
②构造函数模式创建对象
自定义构造函数 问题:方法内存空间浪费/封装不太完善
function sayName(){ //可以有效节省内存空间
console.log(this.name);
}
function Person(name, age, gender){
//this指向new关键字创建的实例
this.name = name;
this.age = age;
this.gender = gender;
sayName: sayName, //将方法写在外面,可以有效节省内存空间
}
var p1 = new Person("terry",11,"man");
console.log(p1)
console.log(p1.constructor); //[Function: Person]
function Dog(name, age, color){
//this指向new关键字创建的实例
this.name = name;
this.age = age;
this.color= color;
sayName: sayName, //将方法写在外面,可以有效节省内存空间
}
var d1 = new Dog("erha",2,"red");
console.log(d1)
console.log(d1.constructor); //[Function: Dog]
③原型模式创建对象
问题: 实例的数据隔离不安全,因为里面的数据共享
function Person(){}
Person.prototype.name = 'zhangsan';
Person.prototype.friends = [];
Person.prototype.sayName = function(){
console.log(this.name);
};
var p1 = new Person();
consoe.log(p1.name); //zhangsan
var p2 = new Person();
consoe.log(p1.name); //zhangsan
p1.friends.push('terry');
console.log(p1.friends); //['terry']
console.log(p2.friends); //['terry']
console.log(p1.sayName === p2.sayName); //true
④组合使用构造函数模式和原型模式
//每个实例自有的放到构造函数中,实例共享的放到原型对象中
function Person(name, age, gender){
//this指向new关键字创建的实例
this.name = name;
this.age = age;
this.gender = gender;
this.friends = [];
}
Person.prototype = { //实例共享的数据
constructor : Person,
sayName:function(){
alert(this.name);
}
}
var p1 = new Person("terry",11,"man");
console.log(p1);
console.log(p1.constructor); //{Function: Person]
var p2 = new Person("larry",11,"woman");
p1.friends.push('hello');
console.log(p1.friends); //['hello']
console.log(p2.friends); //[]
console.log(Person('aaaa')) //undefined, 因为this指针需要指向new关键字,这里只有Person,没有new,所以它没有返回对象,返回的是undefined
28、对象深入了解
①可枚举性:
在打印一个对象,所能看到的属性,这些属性的可枚举性都是true;
for-in循环返回的属性,这些属性的可枚举性也都是true。
②对象的属性类型:
[[Config