js 继承(仿Base.js)

/**
* 在JS的世界,没有真正的class类,只有拷贝和基于原型两种,(注:在 ES2015/ES6 中引入了class关键字,但只是语法糖,JavaScript 仍然是基于原型的)
* 在原型链上查找属性比较耗时,对性能有副作用,这在性能要求苛刻的情况下很重要。另外,试图访问不存在的属性时会遍历整个原型链。遍历对象的属性时,原型链上的每个可枚举属性都会被枚举出来。要检查对象是否具有自己定义的属性,而不是其原型链上的某个属性,则必须使用所有对象从Object.prototype继承的 hasOwnProperty 方法
*
拷贝方式有基于call和apply的构造函数上下文修改、也可以直接克隆对象
 * 下面演示基于原型的继承,记住prototype是
*/
var
Klass = function() {}; Klass.extendClass = (function() { var F = function() {}; return function(C, P) { F.prototype = P.prototype; C.prototype = new F(); C.uper = P.prototype; C.prototype.constructor = C; }; })(); Klass.extend = function(props) { var _slice = Array.prototype.slice; var Glass = function() { /*if (Glass.uper && Glass.uper.hasOwnProperty("init")) { Glass.uper.init.apply(this, _slice.call(arguments)) }*/ if (Glass.prototype.hasOwnProperty("init")) { Glass.prototype.init.apply(this, _slice.call(arguments)); } }; Klass.extendClass(Glass, this); Glass.extend = this.extend; for (var key in props) { if (props.hasOwnProperty(key)) { Glass.prototype[key] = props[key]; } } return Glass; };

example:

var A = Klass.extend({
        init: function(name) {
            this.name = name;
            console.log('A constructor is running!');
        },
        getName: function() {
            return this.name;
        }
    });
    var B = A.extend({
        init: function(name) {
            this.name = name;
            console.log('B constructor is running!');
        },
        getName: function() {
            return this.name;
        },
        a: 'b'
    });
    var C = B.extend({
        init: function(name) {
            console.log('C constructor is running!');
        },
        c: 'c',
        getName: function() {
            var name = C.uper.getName.call(this);

            return 'Hi, I\'m' + this.name;
        }
    });

    var c1 = new C('zlf');
    console.log(c1.getName());

 

posted @ 2015-05-15 11:12  风之约  阅读(200)  评论(0编辑  收藏  举报