【发布时间】:2026-02-03 08:50:01
【问题描述】:
请在 javascript 中考虑此代码:
function Selector() {
this.Status = "";
this.Groups = new Array();
this.Errors = new Array();
}
我想为 Selector 类的 Groups 属性添加一个方法并将其用于任何实例。我该怎么做?
请注意我写了这段代码:
function Selector() {
this.Status = "";
this.Groups = [];
this.Groups.myFunction = function(){alert(this.length);
};
this.Errors = [];
}
var selector = new Selector();
selector.Groups = [1,2,3];
selector.Groups.myFunction();
但是当我设置 Group 属性时,调用方法会出错:
错误:selector.Groups.myFunction 不是函数
我更喜欢找到使用原型对象的方法。
谢谢。
【问题讨论】:
-
this.Groups.myFunction = function(){};.
标签: javascript oop object methods prototype