Javascript 中原型链的封装

对 Javascript 中的原型链做了一个简单的封装,代码如下。

(function(global) {
    let Object = global.Object;
    let ClassPrototype = {
        extend: function(...sources) {
            let PiovanoObject = function() {};
            Object.setPrototypeOf(PiovanoObject, this);
            PiovanoObject.prototype = this.create();
            Object.assign(PiovanoObject.prototype, ...sources);
            Object.defineProperty(PiovanoObject.prototype, 'constructor', {
                value: PiovanoObject,
                enumerable: false
            });
            return PiovanoObject;
        },
        create: function(...sources) {
            let object = Object.create(this.prototype);
            Object.assign(object, ...sources);
            return object;
        }
    }
    let PiovanoObject = function() {};
    Object.setPrototypeOf(PiovanoObject, ClassPrototype);
    global.PiovanoObject = PiovanoObject;
})(typeof window === 'undefined' ? global : window);

代码中使用了 ES6 的部分特性,可能不支持部分版本较老的浏览器。在 Node.js 环境中运行需要加 --es_staging 参数。

以下为简单的测试。

let Animal = PiovanoObject.extend({
    type: 'animal',
    say: function() {
        console.log('I am a(n) ' + this.type);
    }
});
let Cat = Animal.extend({
    type: 'cat'
});
let cat = Cat.create({
    name: 'Lily'
});
let anotherCat = new Cat();
anotherCat.name = 'Another';
//
console.log(Object.getPrototypeOf(Cat.prototype) === Animal.prototype);
console.log(Animal.prototype.isPrototypeOf(Cat.prototype));
console.log(Cat.prototype.__proto__ === Animal.prototype);
//
console.log(Cat.prototype.constructor === Cat);
//
console.log(Object.getPrototypeOf(cat) === Cat.prototype);
console.log(Cat.prototype.isPrototypeOf(cat));
console.log(cat.__proto__ === Cat.prototype);
//
console.log(cat instanceof Cat);
console.log(cat instanceof Animal);
//
console.log(cat.hasOwnProperty('name'));
console.log(cat.hasOwnProperty('type'));
//
cat.type = 'lily cat';
cat.say();
delete cat.type;
cat.say();
//
console.log(Object.getPrototypeOf(anotherCat) === Cat.prototype);
console.log(Cat.prototype.isPrototypeOf(anotherCat));
console.log(anotherCat.__proto__ === Cat.prototype);
//
console.log(anotherCat instanceof Cat);
console.log(anotherCat instanceof Animal);
//
console.log(anotherCat.hasOwnProperty('name'));
console.log(anotherCat.hasOwnProperty('type'));
//
anotherCat.type = 'another cat';
anotherCat.say();
delete anotherCat.type;
anotherCat.say();

发表评论

电子邮件地址不会被公开。 必填项已用*标注