1.2.5.7.Object.create 與純粹的原型繼承
物件建立的方式
3.new運算子
4.Object.create
Object.create
舊的瀏覽器可能不支援
是單純的原型繼承
會用原型建立空物件, 其原型就是傳入Object.create的東西
可以覆寫: 如果想要隱藏預設值, 只要新增相同名稱的屬性跟方法到新物件, 而不會改變原型的屬性
var person = {
firstname: 'Default',
lastname: 'Default',
greet: function(){
return 'Hi' + this.firstname;
}
}
var john = Object.create(person);
console.log(john);
//印出"Hi Default"
console.log(john.greet);
//可以覆寫
john.fistname = 'John'
john.lastname = 'Doe'
polyfill
將engine缺少的功能加進去
//polyfill
if (!Object.create) {
Object.create = function(o) {
if (argument.length > 1) {
throw new Error('Object.create implementation' + ' onlyaccepts the first parameter.')
}
function F() {}
F.prototype = o;
return new F();
}
}
Last updated
Was this helpful?