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/