Constructor and prototype in javascript

What is the difference between these two codes and which one should I use?

function Test() {}
Test.method = function() {};

With prototype:

function Test() {}
Test.prototype.method = function() {};
+4
source share
6 answers

1st case: static method.

function Test() {}
Test.method = function () { alert(1); };
var t = new Test;
Test.method(); // alerts "1"
t.method(); // TypeError: Object #<Test> has no method 'method'

Second case: instance method.

function Test() {}
Test.prototype.method = function () { alert(1); };
var t1 = new Test;
var t2 = new Test;
t1.method(); // alerts "1"
t2.method(); // alerts "1"
Test.method(); // TypeError: Object function Test() {} has no method 'method'
+5
source

The first example simply assigns functions to a new property Testcalled method. This is nothing special or magic (by which I mean, the language does nothing interesting with it). You can call it a static method because it shares all instances, but this is really just a normal property. (Functions - objects and objects have properties.)

Test prototype , Test. . JavaScript , . prototype , , , Test, .

:

function Test() {}
Test.method = function() {};

var a = new Test();
console.log(a.method); // => undefined

:

function Test() {} 
Test.prototype.method = function() {};

var a = new Test();
console.log(a.method); // => function
+1

Test.

0

( )

function Test() {}
Test.method = function() {};

( )

function Test() {}
Test.prototype.method = function() {};

?

, Test:

t = new Test()

:

t.method()

JavaScript Test, , 3 :

function Test() {} {

    this.a = "hello";
    this.b = "world";
    this.c = function() { alert( this.a + this.b) }

}

, :

Test.prototype.method = function() { console.log('prototype defined method') }

JavaScript t, Test:

Test.method = function() { console.log('something unsual') };

Test.method()  // works
t.method()     // no works
0

, . Test, , .

"" ; , - :

var testInst = new Test();
testInst.method() // Error Undefined is not a function

- i.e.

Test.method();

, , .

0

, . , , .

:

Array.isArray( [] )  //true

[].isArray() //throws a TypeError

a TypeError, isArray() Array.prototype (, , , prototype __proto__).

:
* , , , .
* , , .

0

Source: https://habr.com/ru/post/1526608/


All Articles