如何在JS /var /product.js中重写JS函数?



我正在制作一个Magento扩展,在产品视图页面上调用自定义JS文件。这个自定义JS文件将最后加载,并且需要覆盖/JS/varien/product.js底部的formatPrice()函数。

原来的formatPrice函数如下:

formatPrice: function(price) {
return formatCurrency(price, this.priceFormat);
}

我想用以下代码替换/覆盖这个函数:

formatPrice: function(price) {
if (price % 1 == 0) { this.priceFormat.requiredPrecision = 0; }
return formatCurrency(price, this.priceFormat);
}

我如何在我的自定义JS文件中编写JS代码,以便它将正确覆盖此函数?我对JS不够熟悉,不知道

如果它是全局的那么你可以只写window.formatPrice = myNewFormatPrice;如果它是一个对象的成员那么你可以这样写:anObject.formatPrice = myNewFormatPrice;

如果你需要编辑一个对象的原型使用:Product.OptionsPrice.prototype.formatPrice = myFormatPrice;

您还需要查看对requiredPrecision的访问。如果它是"private"或"protected",那么你将无法访问它。

虽然@jholloman的答案从功能的角度来看是正确的,但您可以考虑使用Prototype的方式,从Product.OptionsPrice继承并使用那个新类。这是来自appdesignfrontendbasedefaulttemplatecatalogproductview.phtml,第36行(我假设您需要更改它):

原来

<script type="text/javascript">
    var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
</script>
修改

<script type="text/javascript">
    var MyOptionPrice = Class.create(Product.OptionsPrice, { // inherit from Product.OptionsPrice
        formatPrice: function($super, price) { // $super references the original method (see link below)
            if (price % 1 === 0) { 
                this.priceFormat.requiredPrecision = 0; 
            }
            return $super(price);
        }        
    });
    var optionsPrice = new MyOptionPrice(<?php echo $this->getJsonConfig() ?>); // use yours instead
</script>

使用wrap()(这样,您不必更改原始方法名称):

<script type="text/javascript">
    Product.OptionsPrice.prototype.formatPrice = Product.OptionsPrice.prototype.formatPrice.wrap(function(parent, price) {
        if (price % 1 === 0) { 
            this.priceFormat.requiredPrecision = 0; 
        }
        return parent(price);        
    });
    var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
</script>

查看Prototype继承和$super var的链接。
再一次,我看到了类似于Magento中使用的@jholloman的建议的代码,所以按照他的方式去做没有问题,但我认为你可能想知道如何做这个原型的方式。

最新更新