js中定义一个方法使用.prototype 这样定义getConfig:function 时如何定义一个私有方法
时间: 2024-02-27 07:52:54 浏览: 29
如果你想在使用 `.prototype` 定义的方法中定义一个私有方法,你可以使用闭包来实现。
下面是一个示例代码:
```
function MyClass() {
// 私有方法
var privateMethod = function() {
console.log("This is a private method.");
}
// 公共方法
this.getConfig = function() {
// 调用私有方法
privateMethod();
// 公共方法逻辑
console.log("This is a public method.");
}
}
MyClass.prototype.someOtherMethod = function() {
// 调用 getConfig 方法
this.getConfig();
}
var myObject = new MyClass();
myObject.someOtherMethod(); // This is a private method. This is a public method.
```
在上面的代码中,`privateMethod` 是一个私有方法,只能在构造函数内部访问。`getConfig` 是一个公共方法,可以访问 `privateMethod`。通过将 `getConfig` 定义为一个构造函数上的实例方法,它可以在 `MyClass` 的所有实例中使用。
注意,如果你在使用 `.prototype` 定义方法时,定义了一个私有方法,那么这个私有方法只能在同一个使用 `.prototype` 定义的方法中使用,不能在其他方法中使用。