我试图在构造函数中调用方法,是不可能还是我错过了什么?
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
console.log(this.height);
return this.height * this.width;
};
this.calcArea(); // trying to do it here, its invoked but no result
}
var newone = new Rectangle(12,24);
答案 0 :(得分:1)
您可以尝试这样的事情:
function Rectangle(height, width) {
var self = this;
self.height = height;
self.width = width;
self.calcArea = (function() {
console.log(this.height);
return self.height * self.width;
})();
}
var newone = new Rectangle(12,24)
console.log(newone.calcArea);
答案 1 :(得分:0)
它工作得很好。您没有使用返回的值。
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
console.log(this.height);
return this.height * this.width;
};
var area =this.calcArea(); // trying to do it here, its invoked but no result
console.log(area); //288
}
var newone = new Rectangle(12,24);