Javascript:使用性能参数对函数进行原型(prototype)设计

标签 javascript optimization prototype

John Resig 在 Simple "Class" Instantiation in Javascript 上的帖子中,他说:

"...如果您有一个经常访问的函数(返回一个对象),您希望人们与之交互,那么将对象属性放在原型(prototype)链中并实例化它对您有利。在这里, 在代码中:"

// Very fast
function User(){}
User.prototype = { /* Lots of properties ... */ };
// Very slow
function User(){
    return { /* Lots of properties */ };
}

我想将其应用于如下函数(它恰好存在于“类”声明中)

//...
this.get_subscription = function(args)
{
    return {
        property_one: "value",
        property_two: {
            sub_prop: args.something
        }
    }
}

但不知道将参数放在哪里。如果我这样做

this.get_subscription = function(args) {}
this.get_subscription.prototype = {
    property_one: "value"
    //...
}

它会说 args 未定义。我尝试了几种变体,但都不起作用。我应该如何以不将 args 放入父类范围的方式正确地执行此操作?

最佳答案

您似乎误解了prototype 的意义。原型(prototype)包含对象的所有实例应该共有的方法和字段。因此,如果 property_two 是基于传递给构造函数的 args,那么它属于原型(prototype)!

毕竟,在这段代码中

this.get_subscription = function(args) {}
this.get_subscription.prototype = {
    property_one: "value"
    //...
}

首先,函数 get_subscription 被创建,然后它的原型(prototype)被设置为对象字面量。在调用构造函数之前没有 args,因此在原型(prototype)中使用 args 做一些事情是没有意义的。

因此,您常用的 javascript 对象应该类似于此示例 - 一个 2D 点类。

function Point(x, y) {
    /*  In constructor:
     *  initialize fields that are related to the constructor parameters
     *  and are different for different instances
     */
    this.x = x;
    this.y = y;
}

// in prototype, define fields that are  common to all instances
Point.prototype.RED = '#FF0000';

/*  in prototype, also define the methods; as they can use the "this" keyword,
 *  they can reference their own instance, so you don't have to include them
 *  in each instance manually
 */

Point.prototype.toString = function() { return '[' + this.x + ', ' + this.y + ']'; };

关于Javascript:使用性能参数对函数进行原型(prototype)设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10423051/

相关文章:

javascript - 滚动 div - 带有 javascript 的 css

Javascript替换字符串字符

javascript - 如何使移动设备中的 jquery setinterval 移动更顺畅?

MySQL self-join with order by optimization

javascript - 关于原型(prototype)继承的澄清

javascript - 原型(prototype)对象中的 "get"是什么意思?

javascript - 单击和滚动顶部条件不能同时工作

php - Zend AMF 优化;技巧和窍门?

c++ - 超过 5 个参数的绳索表达模板无法正确内联

javascript - JS __proto__ 继承替换