Javascript没有正确扩展类

时间:2014-06-06 16:11:33

标签: javascript oop inheritance

我已经编写了这段代码,但我没有为任何真正的函数设置我只是定义一个结构

function Finder(d) {
this.ajax = {
    current : null,
    call : function(url,data) {
        //Todo Ajax Code here
    },
    success : function() {
        //Todo: Default Ajax Success Functiality
    },
    error : function(xhr, ajaxOptions, thrownError) {
        //Todo: Default Ajax Failure Functionality
    }
};
d.constructor.extend = function(def){
    for (var k in d) {
        if ( !def.hasOwnProperty(k)) {
            def[k] = d[k];
        }
        return Finder(def);
    }
}
return (d.constructor.prototype = d).constructor;
}

var ModelInput = Finder({
constructor: function() {
    //Todo: Setup functionality
},
registerEvents : function() {
    //Todo: Register Dom Events for ModelInput
}
});



var foo = new ModelInput();

foo的控制台输出;

Finder.constructor {constructor: function, registerEvents: function}
__proto__: Object
constructor: function () {
registerEvents: function () {
__proto__: Object

我的问题是为什么我实例化new ModelInput();时不包含Finder();的方法和属性?

2 个答案:

答案 0 :(得分:0)

  1. Javascript没有遗传 - 只能为原型添加功能

  2. 您的代码也有点乱,用其他原型的某些方法创建原型的最简单方法是

    function A( ) {
        doSomethingWithThis..
    }
    
    A.prototype = { ... }
    
    function B( ) {
        A.call( this );
    }
    
    B.prototype = new A();
    
    B.prototype.method = function() {
    
    }
    
  3. PS。再一次--Javascript不是经典的OOP语言,所以考虑重新设计你的概念以使用工厂方法,例如

        function getFinder( ) {
            var thisObj = {};
    
            thisObj.someFunction = someFunction.bind( thisObj );
    
            return thisObj;
        }
    

答案 1 :(得分:0)

好的,所以我能够做到这一点的唯一方法是使用原型设计..所以我所做的就是这个...

http://jsfiddle.net/b2JM8/

// used for extending classes into new classes
Function.prototype.Implement = function (base) {
    var c = Function.prototype.Implement.nonconstructor;
    c.prototype = new base();
    this.prototype = new c();
};
Function.prototype.Implement.nonconstructor = function () { };


var BaseClass = function() {

    var me = this;

    me.BaseMethodOne = function () {
       alert('BaseMethodOne');
    };

    me.BaseMethodTwo= function () {
        alert('BaseMethodTwo');
    };
}


var MyClass = function() {

    var me = this;

    me.MyMethodOne = function () {
       alert('MyMethodOne ');
    };

    me.MyMethodTwo= function () {
        alert('MyMethodTwo');
    };
}

MyClass.Implement(BaseClass);


var myObject = new MyClass();

myObject.BaseMethodOne();
myObject.BaseMethodTwo();
myObject.MyMethodOne();
myObject.MyMethodTwo();