使用JavaScript的原型的公共方法

时间:2015-01-20 22:18:36

标签: javascript

我希望使用return语句为javascript函数创建公共和私有方法。

我喜欢使用return来传递可公开访问的方法,因为很容易在一个地方看到所有公共属性和方法。

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();

我知道如果我这样做,我将获得公共/私人方法,但我想知道是否有人知道如何使用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();

1 个答案:

答案 0 :(得分:1)

没有。如果要使用原型继承,则不能使用return,应使用this,因为它是从原型继承的实例对象。

当然,没有什么能阻止你在构造函数的末尾聚集你的公共接口:

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

相关问题