ey dee ey em
ey dee ey em

Reputation: 8593

try to build a javascript library but fail to do the simple initiate it

I thought I knew lots stuff about javascript... However this simple library test I try to build is not even seems recognized by javascript. I wonder what is the issue? Is this even the right way to do it? or its better to create it with a closure of (function mylib(){..})? I tried both, all have issues, this one is the approach I attempted, but received load of undefined errors. Don't know what is the exact issue here, some hint will be really appreciated!

function mylib (){
    this.localVar1="One";
    this.localVar2="Two";
    this.funct1 = function (){
        console.log("func1 output"+this.localVar1)
    }
    this.func2 = function (){
        console.log("func2 output"+this.localVar2)
    }
}

var item = new mylib();
    console.log(item.localVar2,"var2");
    console.log(item.func2(),"func2");

Upvotes: 0

Views: 30

Answers (1)

atmd
atmd

Reputation: 7490

You just need to reference the object the properties belog to:

function mylib (){
    this.localVar1="One";
    this.localVar2="Two";
    this.funct1 = function (){
        console.log("func1 output " + this.localVar1)
    }
    this.func2 = function  (){
        console.log("func2 output " + this.localVar2)
    }
}

Also, be aware that functions that have no return value (like your funct1 and func2) will show undefined in dev tools, so console.log(item.func2()); will put undefined in your console. it's not an error, it's just because the function doesnt return a value.

if you change it to:

this.func2 = function  (){
    return "func2 output = " + localVar2;
}

You'll notice the difference

Upvotes: 2

Related Questions