代码中的原型.js和习语

Prototype.js and idiom in code?

本文关键字:习语 js 原型 代码      更新时间:2023-09-26

我有很多使用Prototype's Object.extend的代码。它看起来像这样...

var x = Class.create();
Object.extend(
    Object.extend( x.prototype, Ajax.Application.Base.prototype ),
    { ... stuff ... }
);

现在Object.extend的签名是Object.extend(destination, source) → Object

因此,我们正在用Ajax.Application.Base.prototype扩展x.prototype。然后我们扩展该对象(x.prototype)。用更多的东西。

这与双扩展()相同吗?将它们组合在一起有什么好处?

这些是这样的关联吗..

Object.extend(x,y); Object.extend(x,z) == Object.extend(Object.extend(x,y),z);

回答您的问题 - 是的,Object.extend 确实返回了新对象,该对象具有作为参数传递的 2 个对象的所有方法和属性。

但是,有一种更有用和简洁的方法来扩展PrototypeJS类

(从我的另一个答案中复制一点 https://stackoverflow.com/a/15527223/341491)

var myChildClass = Class.create(myClass,
{
    initialize : function($super,option)
    {
        $super(option);
        // the child class needs option's default value at 150 or whatever is 
        // passed so run the parent initialize first and then redefine the 
        // option property
        this.option = (option ? option : 150);
        // you can still run methods in the parent that are not overridden in 
        // the child
        this.testme();
    }
});
var child = new myChildClass();
child.showme();
//will alert() 151 and return 151

这将创建一个名为 myChildClass 的类,该类是从 myClass 扩展而来的。此方法的区别在于能够使用指向父类的 $super() 方法。