It depends how you wan't to make it / use it.
Easiest fix (but maybe not the best, because you should avoid defining global variables) is to move your var test = "something";
declaration outside the Object declaration:
// Defined before the Object below, so it works correctly
var test = "something";
var Test = {
showUrlLink: function () {
if (test === "something") {
//Do something
console.log("test is: " + test);
}
}
};
Test.showUrlLink(); // test is: something
Alternatively, you could define test
to be a property of an Object itself. See example below.
Using a JavaScript Object:
var Test = {
test: "something",
showUrlLink: function () {
if (this.test === "something") {
//Do something
console.log("this.test is: " + this.test);
}
}
};
Test.showUrlLink(); // this.test is: something
Finally, you could use a JavaScript Class instead of Object.
Using a JavaScript Class:
/**
* Class definition
*
*/
var Test = function () {
this.test = "something";
};
/**
* Method for showing showUrlLink
*
*/
Test.prototype.showUrlLink = function () {
if (this.test === "something") {
//Do something
console.log("this.test is: " + this.test);
}
};
// How to use the Class
var test1 = new Test();
test1.showUrlLink(); // this.test is: something
var test2 = new Test();
test2.showUrlLink(); // this.test is: something
All in all, I usually prefer Classes over Objects, but only if I find myself defining multiple functions inside an Object. Moreover, Classes lets you create multiple instances.
Finally, JavaScript doesn't actually have "classes" but people (like me) use to refer them as Classes instead of constructor functions. More about it in this link.
Cheers.