【问题标题】:Jquery: extend an object to modify a methodJquery:扩展对象以修改方法
【发布时间】:2012-06-10 23:42:13
【问题描述】:

我正在尝试扩展一个对象,我想修改第一个方法,而不是覆盖它。我不认为这很清楚,所以这里是一个例子:

var object1 = {
    whatever : function(){
        console.log('first object method');
    }
}

var object2 = {
    whatever : function(){
        console.log('second object method');
    }
}

var object = $.extend(true, object1, object2);

object.whatever();

这个例子会输出second object method,但我想要的是输出first object methodsecond object method

有没有办法做到这一点?

【问题讨论】:

  • 这就是示例显示的内容:当您在两个对象中定义两个具有相同名称的方法时,第一个不会被触发。我想要 PHP 中的 parent::whatever() 之类的东西
  • 虽然 JS 没有调用超类的内置方式,但您可以使用 here 描述的技术来实现。
  • 不,extends 没有“扩展”功能,这不是它的设计初衷。
  • $.extend 不能那样工作。它只是在有重复项时替换属性。

标签: javascript jquery oop


【解决方案1】:

Javascript使用原型继承,所以可以通过这样做让object2继承object1的属性和方法

object2.prototype=object1;

这意味着object2会继承object1的所有属性和方法,任何被覆盖的方法都可以在object2.prototype.method()访问

所以parent::whatever();在从object2的作用域调用时等价于this.prototype.whatever();


var object1 = {
    whatever : function(){
        console.log('first object method');
    }
}

var object2 = {
    whatever : function(){
        console.log('second object method');
        this.prototype.whatever(); // Equivalent to parent::whatever(); 
    }
}

object2.prototype=object1; // Makes object2 inherit object1's properties and methods

object2.whatever(); // "second object method" "first object method"

【讨论】:

  • 我必须在哪里添加object2.prototype=object1;?在第二个对象中还是之后?
  • 不像我想的那么简单,因为在应用程序中我正在处理的第一个对象将被扩展多次,但它可以工作,谢谢!
  • 如果需要多次扩展,使用原型链。所以 object2.prototype=object1; object3.prototype=object2;对象 3 将首先从对象 2 继承,然后从对象 1。
猜你喜欢
  • 2012-10-28
  • 2015-03-09
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
相关资源
最近更新 更多