2015-12-24 2 views
-1

Im пытается вызвать метод внутри конструктора, разве это невозможно или я что-то пропустил?Могу ли я вызвать this.method в функции конструктора

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

Это работает очень хорошо, но то, что вы ожидаете должно произойти с возвращенного результата из 'Calcarea()'? – adeneo

+0

kinda надеется на newone.calcArea будет результатом 12 * 24 –

+0

'console.log (this.calcArea())' обновление к этому. – Jai

ответ

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); 
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);

Смежные вопросы