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)不是class的成员,所以如果要将其作为函数调用,必须为其指定上下文。

function myClass() {
    function privateFunction () {
        this.publicFunction();
    }

    privateFunction.call(this);
    document.write(this.publicFunction2()); // show value in Whosebug snippet
}

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

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

var myClassPrototype = new myClass();

您不能访问它,因为它在私有函数中。 像这样尝试:

function myClass() {
    function privateFunction () {

    }

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

}

那么如果你这样做

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

您可以看到警报

为了继承 class 你还需要一些其他的东西。这是一个完整的例子。

下面是相关的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/

闭包还不够吗?

首先,我会按照惯例将 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(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 中阅读一些关于 public vs private vs privileged members 的内容。喜欢这篇文章:http://javascript.crockford.com/private.html

要点:

  1. Public(原型)成员无权访问私有
  2. 特权 (this) 成员可以访问私有。
  3. 私有函数可以通过传递的上下文参数访问特权和 public 成员。