簡體   English   中英

如何在JS中公開成員變量的公共方法

[英]how to expose public methods of member variables in JS

我上課了

function A()
{
   var that = this;
   var b = new B(); 
   this.setBSize = function(newSize)
   {
      b.setSize(newSize);
   }


};

function B()
{
   var that = this;

   this.setSize = function(newSize)
   {
   ...
   }
}

a = new A();
a.setBSize(5);

如何避免編寫setBSize方法? 如何自動公開b的公共方法? 我想這樣打電話

a.setSize(5);

我還需要一個new B();的引用new B(); 哪個是A()里面A() b A()

你總是可以設置的原型AB ,如果你想繼承所有方法B

function A() {
    var that = this;
};

function B() {
    var that = this;

    this.setSize = function (newSize) {
        console.log(newSize); // 5
    }
}

A.prototype = new B();

a = new A();
a.setSize(5);

小提琴

jQuery$.extend(that, new B()); angularangular.extend(that, new B());

function A()
{
   var that = this;
   $.extend(that, new B());
};

function B()
{
   var that = this;

   this.setSize = function(newSize)
   {
   ...
   }
}

a = new A();
a.setSize(5);

如果你想在B()類中使用任何private變量,則將它們定義為var someVar ,將所有公共(可that.somePublicVar )變量定義為that.somePublicVar

你可以使用call方法:

function A() {
    var that = this;
    B.call(this);
};

function B() {
    var that = this;
    this.setSize = function (newSize) {
        this.size = newSize;
    }
}

var a = new A();
a.setSize(5);

基本上你調用B在上下文A ,什么情況是,所有的自身屬性B實例都將被分配到this這是A實例。 這種模式稱為構造函數或方法借用。

你應該利用原型。

創建一個在所有類(對象)之間共享函數的構造函數:

var myConstructor = function(newSize){

   this.setSize = function(newSize)
   {
   ...
   }
}

現在你做instanciation:

var a = new myConstructor(someSize);

var b = new myConstrucotr(someSize);

現在有了這個改變, a.setSize()b.setSize()

使用prototype繼承方法setSize並丟棄所有thisthat代碼。

function B() {
};
function A() {
    B.call(this);
};

B.prototype.setSize = function(newSize) {
    console.log(newSize);
}

A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
var a = new A();
a.setSize(5);               // 5
console.log(a instanceof A);// true
console.log(a instanceof B);// true

暫無
暫無

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

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