代码之家  ›  专栏  ›  技术社区  ›  Macha

有没有一种方法可以从Javascript中的函数中更改原型?

  •  2
  • Macha  · 技术社区  · 15 年前

    我用Javascript编写了这种类型的原型继承代码。

    function A() {
        this.a = 1;
    }
    function B() {
        someEl.innerHTML(this.a);
    }
    B.prototype = new A();
    

    但是,我想知道是否有更好的方法,最好是将原型声明引入到 B .

    我试着设置 this.prototype 在里面 ,但它只是显示 this.a undefined

    4 回复  |  直到 15 年前
        1
  •  4
  •   Community CDub    8 年前

    这个 prototype 属性只能用于 constructor functions , this.prototype this 只是新的对象实例,而不是构造函数。

    分配 原型 new B(); ).

    原型 构造函数的属性,就像用 B.prototype = new A(); constructor 的对象实例的属性 B ,将指向 A .

    通常建议恢复该属性,例如:

    function A() {
        this.a = 1;
    }
    
    function B() {
        someEl.innerHTML(this.a);
    }
    
    B.prototype = new A();
    B.prototype.constructor = B; // restore the `constructor` property
    
    var foo = new B;
    foo.constructor === B; // true
    

    看看:

        2
  •  0
  •   tcooc    15 年前

    尝试:

    function A() {
        this.a = 1;
    }
    function B() {
        this.prototype = new A();
        someEl.innerHTML(this.A.a); //notice A.a
    }
    
        3
  •  0
  •   Georg Schölly Crazy Developer    15 年前
    function MyClass() {
        this.initialize();
    }
    
    MyClass.prototype = {
        initialize: function() {               // adding a function name
            this.some_var = "Blue";            // makes debugging easier
        },
        tell_color: function() {
            alert(this.color);
        },
        color: "red"
    }
    
    var instance = new MyClass();
    instance.tell_color();
    

    这不是我的主意,但我不知道我在哪里找到的。

        4
  •  0
  •   G. Shearer    15 年前

    JS中的继承有点奇怪,但是其他人都认为不应该将原型放在构造函数中。原型函数/vars的要点是,对于所述类的所有实例,您只有该函数的单个实例可供使用。同样,它也适用于类vars,一个每个实例都将引用的奇异值。

    实际上,您应该让类B从类A继承:

    function B(){
         this.object = new A();
    }
    
    B.prototype.a = function(){
         return object.a;
    }
    

    function breakApart(what){
         var functions = [];
         var properties = [];
    
         for(property in what){
             if(typeof what[property] == 'function'){
                 functions.push({'name':property,'value':what[property]});
             }else{           
                 properties.push({'name':property,'value':what[property]});
             }
         }
    
         var data = [
             {'title':'functions','data':functions},
             {'title':'properties', 'data':properties}
             ];
    
         return data;
    }
    

    添加几个eval()调用和一些逻辑,就可以让这个函数构建新的getter/setters/函数引用。