Javascript:类构造函数基础知识 - 在单独的方法中定义属性

标签 javascript function class

原来的问题被搁置了,所以这里用不同的措辞进行了一次新的尝试。我希望,现在变得更清楚了:

问题:如何使用私有(private)方法而不是使用原型(prototype)来执行以下操作?

function numberPlusFive(nr) {
    this.number = number + 5;
    this.square = this.calculateSquare();
    this.isPrime = this.checkIfPrime();
}
numberPlusFive.prototype = {
    calculateSquare: function() {
        return this.number * this.number;
    },
    checkIfPrime: function() {
        // check if this.number is a prime number
        return true; // or false
    },
}

一旦构造了类,就不再需要方法(calculateSquare、checkIfPrime)。我想用单独的方法进行计算,但不需要将这些方法公开。

重要提示:我需要已经计算出的属性来进行进一步计算(因此在本例中,this.number 必须calculateSquarecheckIfPrime 中可用 - 并且不,我不能只是重新计算this.number,因为在真实的脚本中,需要很长时间才能计算。)。

最佳答案

您可以在构造函数中声明calculateSquare和checkIfPrime函数并返回另一个对象。

function myFirstJsClass(number) {

    var calculateSquare = function(n) {
        return n * n;
    };

    var checkIfPrime = function(n) {
        //check if prime
        return true; // or false
    };

    this.number = number;
    this.square = calculateSquare(number);
    this.isPrime = checkIfPrime(this.square);

}

或者,您也可以在外部声明它们并在构造函数中调用它们。

var calculateSquare = function(n) {
    return n * n;
};

var checkIfPrime = function(n) {
    //check if prime
    return true; // or false
};

function myFirstJsClass(number) {
    this.number = number;
    this.square = calculateSquare(number);
    this.isPrime = checkIfPrime(this.square);
}

如果您不想将所有内容作为参数传递,您也可以使用 call() http://www.w3schools.com/js/js_function_invocation.asp 调用该函数

var calculateSquare = function() {
    this.square= this.number * this.number;
};

var checkIfPrime = function() {
    //check if prime with this.square
    this.isPrime = true; // or false
};

function myFirstJsClass(number) {
    this.number = number;
    calculateSquare.call(this);
    checkIfPrime.call(this);
}

关于Javascript:类构造函数基础知识 - 在单独的方法中定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134691/

相关文章:

javascript - 如何在多日期选择器插件中显示月份名称?

c++ - 如何使主函数可以访问函数中的变量?

javascript - 未定义不是带有组合框的函数

python - 收到错误消息说 super 需要 1 个参数,但给出了 0 个参数?

c++ - 带有指针成员的类

c++ - 将 lambda 放入类定义中的简洁方法

javascript - 根据更改的数字显示/隐藏嵌套在不同 div 中的相同 div 类

javascript - 同步多选框中的两个滚动条

javascript - 使用 D3 为 svg 填充背景图像

c++ - 用 C++ 编写基于字符串的事件管理器