简体   繁体   English

如何在完全独立的.js文件中覆盖/扩展prototype.js类

[英]How do I override / extend a prototype.js class in a completely seperate .js file

I have a prototype.js class that I would like to extend to both add some new functions and override a couple of the functions already there. 我有一个prototype.js类,我想扩展到添加一些新函数并覆盖已经存在的几个函数。

in the example below I would like to add initAutocompleteNew and edit initAutocomplete to alert "new". 在下面的示例中,我想添加initAutocompleteNew并编辑initAutocomplete以警告“新”。

Varien.searchForm = Class.create();
Varien.searchForm.prototype = {
    initialize : function(form, field, emptyText){
        this.form   = $(form);
        this.field  = $(field);
        this.emptyText = emptyText;

        Event.observe(this.form,  'submit', this.submit.bind(this));
        Event.observe(this.field, 'focus', this.focus.bind(this));
        Event.observe(this.field, 'blur', this.blur.bind(this));
        this.blur();
    },
//////more was here

    initAutocomplete : function(url, destinationElement){
            alert("old");
    },
}

someone suggested but that doesn't work I think it's jQuery? 有人建议,但这不起作用我认为这是jQuery?

$.extend(obj_name.prototype, {
    newfoo : function() { alert('hi #3'); }
}

This article should help out: http://prototypejs.org/learn/class-inheritance 本文应该有所帮助: http//prototypejs.org/learn/class-inheritance

It looks like you're defining your classes the 'old' way as described in the first example on that page. 看起来您正在按照该页面上第一个示例中所述的“旧”方式定义您的类。 Are you using 1.7? 你使用的是1.7吗?

Assuming you are using 1.7, if you wanted to override or add methods to your class, you can use Class.addMethods : 假设您使用的是1.7,如果要覆盖或向类添加方法,可以使用Class.addMethods

Varien.searchForm.addMethods({
  initAutocomplete: function(url, destinationElement) {
    // Your new implementation
    // This will override what was previously defined
    alert('new');
  },
  someNewMethod: function() {
    // This will add a new method, `someNewMethod`
    alert('someNewMethod');
  }
});

Here's a fiddle: http://jsfiddle.net/gqWDC/ 这是一个小提琴: http//jsfiddle.net/gqWDC/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM