对象创建方式
1.对象直接量
var person={
name="oBa";
sex='man';
}
[[prototype]]指向Object.prototype
2.new方法,与1类似
var person=new Object();
person.name='oBa';
person.sex='man';
[[prototype]]指向Object.prototype
3.工厂方式 ,少见了
var createPerson = function(name,age,job){
var person = new Object();
person.name = name;
person.age = age;
person.job = job;
person.sayName = function(){
alert(person.name);
}
return person;
}
var person1 = createPerson("oBa","18","mokey");
person1.sayName(); // oBa
person1的[[prototype]]指向Object.prototype
4.构造函数
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
};
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person("oBa",18,"bape");
person1.sayName();
person1的[[prototype]]指向Person.prototype,
Person.prototype的[[prototype]]指向Object.prototype,
这里面多了一层,有new就是不一样
5.由Object.create()方法创建//es5
var person={
name="oBa";
sex='man';
}
var person1=Object.create(person);
person1的[[prototype]]指向person
Object.create()内部大概原理:
Object.create=function(p){
function F(){};
F.prototype=p;
return new F();
}
.proto===.constructor.prototype不一定正确
例如一个对象通过Object.create()创建,则不成立