132

如果它被覆盖,是否可以从 JavaScript 中的原型方法调用基本方法?

MyClass = function(name){
    this.name = name;
    this.do = function() {
        //do somthing 
    }
};

MyClass.prototype.do = function() {  
    if (this.name === 'something') {
        //do something new
    } else {
        //CALL BASE METHOD
    }
};
4

14 回答 14

205

我不明白你到底想做什么,但通常实现对象特定的行为是按照以下方式完成的:

function MyClass(name) {
    this.name = name;
}

MyClass.prototype.doStuff = function() {
    // generic behaviour
}

var myObj = new MyClass('foo');

var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
    // do specialised stuff
    // how to call the generic implementation:
    MyClass.prototype.doStuff.call(this /*, args...*/);
}
于 2009-02-18T12:55:49.427 回答
24

一种方法是保存基本方法,然后从覆盖的方法中调用它,就像这样

MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){  

    if (this.name === 'something'){

        //do something new

    }else{
        return this._do_base();
    }

};
于 2009-02-18T13:25:23.740 回答
16

恐怕你的例子不像你想的那样起作用。这部分:

this.do = function(){ /*do something*/ };

覆盖定义

MyClass.prototype.do = function(){ /*do something else*/ };

由于新创建的对象已经具有“do”属性,因此它不会查找原型链。

Javascript 中的经典继承形式很尴尬,而且难以掌握。我建议改用 Douglas Crockfords 的简单继承模式。像这样:

function my_class(name) {
    return {
        name: name,
        do: function () { /* do something */ }
    };
}

function my_child(name) {
    var me = my_class(name);
    var base_do = me.do;
    me.do = function () {
        if (this.name === 'something'){
            //do something new
        } else {
            base_do.call(me);
        }
    }
    return me;
}

var o = my_child("something");
o.do(); // does something new

var u = my_child("something else");
u.do(); // uses base function

在我看来,这是一种在 javascript 中处理对象、构造函数和继承的更清晰的方法。您可以在 Crockfords Javascript: The good parts中阅读更多内容。

于 2009-02-18T13:26:32.253 回答
10

我知道这篇文章是 4 年前的,但由于我的 C# 背景,我一直在寻找一种方法来调用基类,而不必指定类名,而是通过子类上的属性获取它。所以我对克里斯托夫的回答的唯一改变是

由此:

MyClass.prototype.doStuff.call(this /*, args...*/);

对此:

this.constructor.prototype.doStuff.call(this /*, args...*/);
于 2013-09-04T15:05:26.420 回答
5

如果您定义这样的函数(使用 OOP)

function Person(){};
Person.prototype.say = function(message){
   console.log(message);
}

调用原型函数有两种方法: 1)创建实例并调用对象函数:

var person = new Person();
person.say('hello!');

另一种方法是...... 2)直接从原型调用函数:

Person.prototype.say('hello there!');
于 2014-08-13T22:01:53.880 回答
5

该解决方案使用Object.getPrototypeOf

TestA是超级有getName

TestB是一个覆盖getName但也有 getBothNames调用super版本getName以及child版本的孩子

function TestA() {
  this.count = 1;
}
TestA.prototype.constructor = TestA;
TestA.prototype.getName = function ta_gn() {
  this.count = 2;
  return ' TestA.prototype.getName is called  **';
};

function TestB() {
  this.idx = 30;
  this.count = 10;
}
TestB.prototype = new TestA();
TestB.prototype.constructor = TestB;
TestB.prototype.getName = function tb_gn() {
  return ' TestB.prototype.getName is called ** ';
};

TestB.prototype.getBothNames = function tb_gbn() {
  return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);
};

var tb = new TestB();
console.log(tb.getBothNames());

于 2016-08-21T08:08:34.277 回答
4
function NewClass() {
    var self = this;
    BaseClass.call(self);          // Set base class

    var baseModify = self.modify;  // Get base function
    self.modify = function () {
        // Override code here
        baseModify();
    };
}
于 2013-12-07T19:56:43.307 回答
4

替代 :

// shape 
var shape = function(type){
    this.type = type;
}   
shape.prototype.display = function(){
    console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){ 
    // call implementation of the super class
    this.__proto__.display.apply(this,arguments);
}
于 2015-11-13T16:57:54.043 回答
2

如果我理解正确,您希望始终执行基本功能,而其中一部分应该留给实现。

您可能会从“模板方法”设计模式中获得帮助。

Base = function() {}
Base.prototype.do = function() { 
    // .. prologue code
    this.impldo(); 
    // epilogue code 
}
// note: no impldo implementation for Base!

derived = new Base();
derived.impldo = function() { /* do derived things here safely */ }
于 2009-02-18T13:11:00.950 回答
1

如果你知道你的超类的名字,你可以这样做:

function Base() {
}

Base.prototype.foo = function() {
  console.log('called foo in Base');
}

function Sub() {
}

Sub.prototype = new Base();

Sub.prototype.foo = function() {
  console.log('called foo in Sub');
  Base.prototype.foo.call(this);
}

var base = new Base();
base.foo();

var sub = new Sub();
sub.foo();

这将打印

called foo in Base
called foo in Sub
called foo in Base

正如预期的那样。

于 2015-02-25T22:56:17.110 回答
1

ES5 的另一种方法是使用显式遍历原型链Object.getPrototypeOf(this)

const speaker = {
  speak: () => console.log('the speaker has spoken')
}

const announcingSpeaker = Object.create(speaker, {
  speak: {
    value: function() {
      console.log('Attention please!')
      Object.getPrototypeOf(this).speak()
    }
  }
})

announcingSpeaker.speak()
于 2016-12-16T13:48:58.140 回答
0

不,您需要为构造函数中的 do 函数和原型中的 do 函数赋予不同的名称。

于 2009-02-18T13:28:59.643 回答
0

此外,如果您想覆盖所有实例而不仅仅是一个特殊实例,这个可能会有所帮助。

function MyClass() {}

MyClass.prototype.myMethod = function() {
  alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
  MyClass.prototype.myMethod_original.call( this );
  alert( "doing override");
};

myObj = new MyClass();
myObj.myMethod();

结果:

doing original
doing override
于 2015-03-26T10:47:51.450 回答
-1
function MyClass() {}

MyClass.prototype.myMethod = function() {
  alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
  MyClass.prototype.myMethod_original.call( this );
  alert( "doing override");
};

myObj = new MyClass();
myObj.myMethod();
于 2015-05-25T04:45:56.993 回答