有点疑惑。这中间发生了什么
迷之疑问,。。。
Object.create创建对象是创建一个拥有指定原型和若干个指定属性的对象,也就是说可以任意指定原型,甚至是null, 而new Object()只是创建了一个以Object.prototype为原型的对象。如果此处你new Object泛指通过new操作符来创建一个实例对象的话,只要运用得当,二者并不太大差别。
Javascript定义类(class)的三种方法
Object.create()方法是ECMAScript5中新增的,用来规范化原型式继承的。
这个方法接收两个参数,一个是用作新对象原型的对象,和一个为新对象定义额外属性的(可选)对象。
var person = {
name : "Nicholas",
friends : ["John", "Jane"] // 引用类型值属性共享
}
var onePerson = Object.create(person); // onePerson继承person对象
onePerson.name = "Greg";
onePerson.friends.push("Mike");
console.log(onePerson.name); // Greg
console.log(onePerson.friends); // ["John", "Jane", "Mike"]
var anotherPerson = Object.create(person);
console.log(anotherPerson.name); // Nicholas
anotherPerson.friends.push("Jacky");
console.log(anotherPerson.friends); // ["John", "Jane", "Mike", "Jacky"]
// 第二个参数对象格式与Object.defineProperties()方法的第二个参数格式相同
var theOtherPerson = Object.create(person, {
name : {
configurable : false, // 不可修改
value : "Greg"
}
});
console.log(theOtherPerson.name); // Greg
theOtherPerson.name = "Bob"; // 失效
console.log(theOtherPerson.name); // Greg
new Object()方法的实质是,使用引用类型Object的构造函数创建了一个新的实例,这个实例拥有Object默认的方法如toString、toLocaleString等。
示例基于JavaScript高级程序设计第三版进行了一些修改。