上述说法不对使用:定义方法时该怎么做
时间: 2023-10-22 08:21:49 浏览: 37
非常抱歉,之前的回答有误。在使用 `.prototype` 定义方法时,如果想定义一个私有方法,可以在构造函数中定义一个私有函数,然后在使用 `.prototype` 定义的方法中调用这个私有函数来实现。
下面是一个示例代码:
```
function MyClass() {
// 私有方法
function privateMethod() {
console.log("This is a private method.");
}
// 公共方法
this.publicMethod = function() {
// 调用私有方法
privateMethod();
// 公共方法逻辑
console.log("This is a public method.");
}
}
MyClass.prototype.someOtherMethod = function() {
// 调用 publicMethod 方法
this.publicMethod();
}
var myObject = new MyClass();
myObject.someOtherMethod(); // This is a private method. This is a public method.
```
在上面的代码中,`privateMethod` 是一个私有方法,只能在构造函数内部访问。`publicMethod` 是一个公共方法,可以访问 `privateMethod`。通过将 `publicMethod` 定义为一个构造函数上的实例方法,它可以在 `MyClass` 的所有实例中使用。
注意,如果你在使用 `.prototype` 定义方法时,定义了一个私有方法,那么这个私有方法只能在同一个使用 `.prototype` 定义的方法中使用,不能在其他方法中使用。