Extend in Javascript
var Book = function(title) {
Object.defineProperty(this, 'title', {
writable: false,
value: title
}); // 创建只读属性
};
Book.prototype.getTitle = function() { return this.title; }; // accessor
var EBook = function(link) {
Object.defineProperty(this, 'link', {
writable: false,
value: link
});
};
EBook.prototype = Object.create(Book.prototype, {
download: {
writable: false,
value: function() { console.log('Start...'); }
}
});
// 一定要修正 constructor
EBook.prototype.constructor = EBook; // WTF??
// testing
var jsorz = new EBook('https://zhuanlan.zhihu.com/ElemeFE');
console.log(jsorz instanceof Book);
console.log(jsorz instanceof EBook);
console.log(jsorz.constructor === EBook);
console.log(jsorz.hasOwnProperty('getTitle') === false);
console.log(Object.getPrototypeOf(jsorz) === EBook.prototype);
console.log(Object.getPrototypeOf(jsorz).constructor === EBook);