簡體   English   中英

使用原型與JavaScript的公共方法

[英]Public methods using prototype with 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();

不能。如果要使用原型繼承,則不能使用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;
}

請注意,您不應使用new Base繼承Child.prototype

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM