簡體   English   中英

Javascript從構造函數內部調用原型函數

[英]Javascript call prototype function from function inside constructor

我搜索這個問題很長一段時間了。 找不到任何答案來滿足我的問題。 我在想的是:

function myClass() {
    function privateFunction () {
        publicFunction();    //Error
    }
}

myClass.prototype.publicFunction = function() {
    this.variable = 1;
}
myClass.prototype.publicFunction2= function() {
    return this.variable;
}

這給了我錯誤。 我沒有得到真正的問題:

我嘗試了什么:

this.publicFunction();

然后:

myClass.publicFunction();

然后:

myClass.prototype.publicFunction();

這有效,但它會覆蓋每個對象。 就像它在不同的JS對象中是靜態的一樣。

您尚未正確聲明原型函數。 調用函數publicFunction時,您也缺少this關鍵字。

私有函數( privateFunction )不是該類的成員,因此如果要將其作為函數調用,則必須為其指定上下文。

 function myClass() { function privateFunction () { this.publicFunction(); } privateFunction.call(this); document.write(this.publicFunction2()); // show value in Stackoverflow snippet } myClass.prototype.publicFunction = function() { this.variable = 1; } myClass.prototype.publicFunction2 = function() { return this.variable; } var myClassPrototype = new myClass(); 

閉合不足夠嗎?

首先,我按慣例將myClass重命名為MyClass

function MyClass() {
    var myInstance = this;

    function privateFunction () {
        // closure 
        myInstance.publicFunction();
    }
}

MyClass.prototype.publicFunction = function() {
    this.variable = 1;
}
MyClass.prototype.publicFunction2= function() {
    return this.variable;
}

現在你應該能夠以這種方式實現它

var myInstance = new MyClass();

現在你可以看到privateFunction從未被調用過,調用它會有點多余,但我只是試圖展示如何在技術上實現它。

您沒有訪問它,因為它在私有函數中。 試試這樣:

function myClass() {
    function privateFunction () {

    }

    this.publicFunction = function() {
         alert('ok')
    }

}

如果你這樣做的話

var obj = new myClass()
obj.publicFunction()

你可以看到警報

為了繼承課程,你需要一些其他的東西。 這是一個完整的例子。

現在這里是相關的js代碼。 把它放在一個文件中測試它:

function Operators() {
    //mandatory
    var self = this

    //private
    var IPT_X = '#x'
    var IPT_Y = '#y'

    //public
    this.x = 0
    this.y = 0    

    this.showOperators = function() {
        //use of a private property (IPT_X) and a public property (this.x)
        $(IPT_X).val(this.x)
        $(IPT_Y).val(this.y)
    }

    this.clean = function() {
        this.x = 0
        this.y = 0
        // call to a local public method 
        this.showOperators()
    }

    this.updateOperators = function(_x, _y) {
        // use of a public property when call from
        // derived class method is necessary
        self.x = _x
        self.y = _y
    }
}

function Randomizer() {
    // mandatory for derived classes
    Operators.call(this)
    // mandatory for overloaded methods with call to the inherited method
    var parentUpdateOperators = this.updateOperators
    var self = this

    // private
    function getRandomNumber() {
        return Math.round(Math.random() * 1000)
    }

    // public
    this.updateOperators = function(_x, _y) {
            // call to inherited method of superior class
        parentUpdateOperators(_x, _y)
            // call to method of superior class
            self.showOperators()
    } 

    this.populateRandomNumbers = function() {
        // call to public local method (this.updateOperators())
        // and to a local private method (getRandomNumber())
        this.updateOperators(getRandomNumber(), getRandomNumber())
    }

    // init
    this.populateRandomNumbers()
}
// Mandatory for derived classes. Allows access to superior classes with
// more than 2 levels of inheritance ("grandfather" classes)
Randomizer.prototype = Object.create(Operators.prototype)

function Operations() {
    Randomizer.call(this)
    var self = this

    //private
    var IPT_RES = '#res'
    var BTN_SUM =  '#sum'
    var BTN_SUBTRACT =  '#subt'
    var BTN_MULTIPLY =  '#mult'
    var BTN_DIVISION =  '#div'
    var BTN_CLEAN =  '#clean'
    var BTN_RAND =  '#rand'

    function calcSum() {
        return self.x + self.y
    } 
    function calcSubtraction() {
        return self.x - self.y
    } 
    function calcMultiplication() {
        return self.x * self.y
    } 
    function calcDivision() {
        return self.x / self.y
    } 

    function showRes(val) {
        $(IPT_RES).val(val)
    }

    //public
    this.sum = function() {
        // call to 2 local private methods
        showRes(calcSum())
    }
    this.subtract = function() {
        showRes(calcSubtraction())
    }
    this.multiply = function() {
        showRes(calcMultiplication())
    }
    this.division = function() {
        showRes(calcDivision())
    }

    // init
    $(BTN_SUM).on('click', function() { self.sum() })
    $(BTN_SUBTRACT).on('click', function() { self.subtract() })
    $(BTN_MULTIPLY).on('click', function() { self.multiply() })
    $(BTN_DIVISION).on('click', function() { self.division() })    
    $(BTN_CLEAN).on('click', function() { self.clean() })
    $(BTN_RAND).on('click', function() { self.populateRandomNumbers() })
}
Operations.prototype = Object.create(Randomizer.prototype)

var obj = new Operations()

如果你打算在這里測試它是html代碼:

X: <input id='x'>
<br>
Y: <input id='y'>
<br>
Res: <input id='res'>
<br>
<input id='sum' type='button' value='+'>
<input id='subt' type='button' value='-'>
<input id='mult' type='button' value='*'>
<input id='div' type='button' value='/'>
<input id='clean' type='button' value='C'>
<input id='rand' type='button' value='Rand'>

不要忘記添加jquery文件。

這是一個帶有該代碼的JSFiddle:

http://jsfiddle.net/vqqrf2cb/24/

嘗試這個:

function myClass() {
  function privateFunction(obj) {
    obj.privilegedFunction1();
  };
  this.privilegedFunction1 = function () {
    this.variable = 1;
  };
  this.privilegedFunction2 = function () {
    privateFunction(this);
  };
}

myClass.prototype.publicFunction2 = function () {
    return this.variable;
}

var test = new myClass();
test.privilegedFunction2();
console.log(test.publicFunction2());

還有這個:

function myClass() {
  function privateFunction(obj) {
    obj.publicFunction1();
  };
  this.privilegedFunction2 = function () {
    privateFunction(this);
  };
}

myClass.prototype.publicFunction1 = function () {
  this.variable = 1;
}

myClass.prototype.publicFunction2 = function () {
    return this.variable;
}

var test = new myClass();
test.privilegedFunction2();
console.log(test.publicFunction2());

您可能想要在Javascript中閱讀一些有關公共與私人和特權成員的內容。 喜歡這篇文章: http//javascript.crockford.com/private.html

關鍵點:

  1. 公共(原型)成員無法訪問私有。
  2. 特權(此)成員可以訪問私人。
  3. 私有函數可以通過傳遞的上下文參數訪問特權成員和公共成員。

暫無
暫無

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

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