Car*_*ano 1 javascript methods visibility
我有一个被调用的对象Grid,我用new它来创建它的实例.我希望能够从外部调用它的方法.
这是(简化)对象:
var Grid = function() {
this.table = createTable();
function createTable() {
// ...
};
function setSelectedLine(line) { // this one should be public
// ...
};
};
var g = new Grid();
g.setSelectedLine(anyLine); // TypeError: g.setSelectedLine is not a function
Run Code Online (Sandbox Code Playgroud)
我发现其他主题有类似的问题,但他们使用非常不同的对象结构.是否有可能将该方法公之于众,而无需重写所有内容?真正的对象实际上比那更大.
小智 6
你可以将它添加到对象原型:
var Grid = function() { .. };
Grid.prototype.methodName = function() { .. };
Run Code Online (Sandbox Code Playgroud)
或者您可以将其添加为构造函数中的属性.
var Grid = function() {
this.methodName = function() { .. };
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |