原来的问题被搁置了,所以这里用不同的措辞进行了一次新的尝试。我希望,现在变得更清楚了:
问题:如何使用私有(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
必须在 calculateSquare
和 checkIfPrime
中可用 - 并且不,我不能只是重新计算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/