JavaScript OOPS Question

There is a newbie to JavaScript here. I have the following code:

function testObject(elem) {
    this.test = "hi";
    this.val = elem;
    console.log(this.test+this.val);
    echo();

    function echo () {
        console.log(this.test+this.val);
    }
}

var obj = new testObject("hello");

When it starts, I expect hihello to be displayed twice in the console. Instead, it displays as expected for the first time, but returns NaN a second time.

I'm sure something is missing here. I thought that an internal function could access the curtains outside. Can someone guide me? I am more a functional user interface developer and do not have much experience with OO code.

Thank!

+3
source share
3 answers

, echo this , this.test this.val ( window.test window.val): undefined.

this , :

echo.call(this);

, echo();, this .

, , this.

: , echo();, this , , :

//...
var instance = this; // save the outer `this` value
function echo (){
  console.log(instance.test+instance.val); // use it
}
echo();
//...

//...
var echo = (function (instance) {
  return function () {
    console.log(instance.test+instance.val);
  };
})(this); // pass the outer `this` value
echo();
//...
+3

:

function testObject(elem) {
    this.test = "hi";
    this.val = elem;
    console.log(this.test+this.val);

    this.echo = function () {
        console.log(this.test+this.val);
    }
    this.echo();
}

var obj = new testObject("hello");

, this.echo() obj.echo(), this , .

+2

Personally, I find it elegant to declare class methods as follows:

function testObject(elem) {
    this.test = "hi";
    this.val = elem;
    this.echo();
}

testObject.prototype = {
    echo: function () {
        console.log(this.test + this.val);
    }
}

var obj = new testObject("hello");
+1
source

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


All Articles