This question is an exact duplicate:

I read this article and can not understand why it does not work:

function test() { this.nameBRO = '123'; this.speedBRO = 555; } test.prototype.goodBRO = function(a) { this.str = a; console.log(this.str); }; 

Actually test.nameBRO can not call, writes Uncaught TypeError:

 test.nameBRO is not a function 

The same speedBRO .

As for goodBRO : test.goodBRO('fd') - this is not called, only if you write test.prototype.goodBRO('fd') .

What am I doing wrong, then everything is just like 5 kopecks, why doesn't it work?

Reported as a duplicate at Grundy. javascript Nov 25 '16 at 8:47 .

This question has been marked as a duplicate of an existing one.

  • goodBRO : (new test()).goodBRO('fd') , only goodBRO nothing to you - Igor

1 answer 1

There are two ways to define a class method (in a post subfunction), functional and prototype.

Functionally, when creating a class, its methods are explicitly specified:

 function test() { //имя класса this.nameBRO = '123'; //свойство класса this.speedBRO = 555; this.goodBRO = function(a) { // ΠΌΠ΅Ρ‚ΠΎΠ΄ класса this.str = a; console.log(this.str); } } 

In this case, the new object

 t = new test() 

looks like that

Object {nameBRO: "123", speedBRO: 555, goodBRO: test / this.goodBRO ()}

In the prototype method is assigned not to the class, but to its prototype, the parent.

 function test() { //имя класса this.nameBRO = '123'; //свойство класса this.speedBRO = 555; } test.prototype.goodBRO = function(a) { // ΠΌΠ΅Ρ‚ΠΎΠ΄ класса this.str = a; console.log(this.str); }; 

In this case, the object looks like this Object {nameBRO: "123", speedBRO: 555}

But the method is invoked in the same way in both cases:

 t = new test() t.goodBRO(12); 
  • add a description of what exactly is happening in response - Grundy