javascript - 通过 JavaScript 使用原型(prototype)的公共(public)方法

标签 javascript

我希望为带有 return 语句的 javascript 函数创建公共(public)和私有(private)方法。

我喜欢使用 return 传回可公开访问的方法的想法,因为可以轻松地在一个地方查看所有公共(public)属性和方法。

var Base = function(){
  var method1 = function(){
    console.log("method1");
  }
  var method2 = function(){
    console.log("method2");
  }
  //private
  var method3 = function(){
    console.log("method3");
  }
  // public methods
  return {
    method1:method1,
    method2:method2
  }
}
var Child = function(){
  var method4 = function(){
    console.log("method4");
  }
  var method5 = function(){
    console.log("method5");
  }
  //private
  var method6 = function(){
    console.log("method6");
  }
  // public methods
  return {
    method4:method4,
    method5:method5

  }
}
Child.prototype = new Base();

var base = new Base();
base.method1();
base.method2();

var child = new Child();
try {
  child.method1();
} catch(e){
  console.log(e.message);
}
try {
  child.method2();
} catch(e){
  console.log(e.message);
}
child.method4();
child.method5();

我知道如果我这样做,我会得到公共(public)/私有(private)方法,但我想知道是否有人知道如何使用 return 语句来做到这一点。

var Base = function(){
  // public methods
  this.method1 = function(){
    console.log("method1");
  };
  this.method2 = function(){
    console.log("method2");
  };
  // private methods
  var method3 = function(){
    console.log("method2");
  };
};
var Child = function(){
  // public methods
  this.method4 = function(){
    console.log("method4");
  };
  this.method5 = function(){
    console.log("method5");
  };
  // private methods
  var method6 = function(){
    console.log("method6");
  };
};
Child.prototype = new Base();

var base = new Base();
base.method1();
base.method2();

var child = new Child();
child.method1();
child.method2();
child.method4();
child.method5();

最佳答案

没有。如果您想使用原型(prototype)继承,则不能使用 return,而应该使用 this,因为它是从原型(prototype)继承的实例对象。

当然,没有什么可以阻止您在构造函数的末尾聚合公共(public)接口(interface):

function Base() {
  function method1() {
    console.log("method1");
  }
  function method2() {
    console.log("method2");
  }
  //private
  function method3() {
    console.log("method3");
  }
  // public methods
  this.method1 = method1;
  this.method2 = method2;
}

请注意,您should not use new Base for the inheritance of Child.prototype .

关于javascript - 通过 JavaScript 使用原型(prototype)的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28056181/

相关文章:

javascript - Kendo 模板源绑定(bind)数组创建双条目

javascript - 运行 angular.js 作为回调(例如 $.ajax)

javascript - 如何使用chrome扩展名编辑YouTube字幕

javascript - 当用户在不同的选项卡中时,jQuery 更改页面的标题

javascript - 如何在 javascript 中连接这些值?

javascript - 在 JavaScript 中添加多个 HTML 表单输入值

javascript - 可见 Html 选择选项显示在隐藏项目下

javascript - 如何使用 jQuery 使 html5 视频播放器静音

javascript - `innerText` 在 Mozilla Firefox 中未定义

JavaScript:循环数组