Trying to create the test method of the MyObject object like this:

<script> function MyObject(){ function test(){}; }; var my = new MyObject(); my.test(); </script> 

Error crashes into console:

TypeError: my.test is not a function

I do not understand what I'm doing wrong?

    2 answers 2

    To create a method in the constructor, add this method to this

     function MyObject(){ this.test = function test(){}; }; var my = new MyObject(); my.test(); 

    Or, if you use ES2015

     class MyObject{ test(){}; }; var my = new MyObject(); my.test(); 

     function MyObject(){ this.test = function test(){ document.write('test from constructor','<br/>'); }; }; var my = new MyObject(); my.test(); class MyObject2015{ test(){ document.write('ES2015: test from constructor','<br/>'); }; }; var my = new MyObject2015(); my.test(); 

    • Thanks for the rescue. - perfect
    • es6 methods are written to the prototype, not to the constructor's insights. It is also worth noting that js is a language built on prototypes and for this reason it is more reasonable to write methods in the prototype. - vas
    • `` `var MyObject = function () {function MyObject () {_classCallCheck (this, MyObject); } MyObject.prototype.test = function test () {}; return MyObject; } (); `` ` - vas
    • So your class will compile to es5. - vas
    • @vas, so what? :) I did not say that the methods will not get into the prototype - Grundy

    Just in case, I would like to draw your attention to the fact that creating methods in the constructor is inefficient in terms of memory. In fact, in the first example, a new function test is created from the @Grundy response when creating each new MyObject object. In most cases, this is an undesirable effect (the use of the constructor, as a closure, I do not specifically consider here).

    In addition, by creating methods in the constructor, you complicate the inheritance mechanism.

    As a result, in most cases it is more correct to bind methods to the prototype of the object being created, namely:

     var MyObject = function(foo) { // Инициализация свойств, уникальных для каждого ЭКЗЕМПЛЯРА MyObject. this.foo = foo; }; MyObject.prototype.test = function() { console.log(this.foo); }; var my = new MyObject('test'); my.test(); // Выведет "test"