Skip to content Skip to sidebar Skip to footer

Dynamically Access Function Object Property

I need to check if the value of multiple textareas is equal to the property name of this object : function make_test(name, job, ID) { test = {}; test.name = name; test.job =

Solution 1:

You need to declare test to be a local variable so all invocations of your function are not referring to the exact same global variable. When you don't declare your variable it becomes an implicit global variable which can lead to all sorts of problems. If you run your code in strict mode, the interpreter will flag this as an error for you too (which is generally helpful).

You also need to assign the return result from your function to a variable so you can reference the newly created object using that variable.

functionmake_test(name, job, ID) {
    var test = {};
 // ^^^
    test.name = name;
    test.job = job;
    test.ID = ID;
    return test;
}
var o1 = make_test("Paul", "manager", 1);
var o2 = make_test("John", "employee", 2);
var o3 = make_test("Jan", "employee", 2);

console.log(o1.name);   // "Paul"console.log(o3.job);    // "employee"

You also don't need new in front of your function since you aren't using a system created object - you are just creating your own object and returning it. It will still work with new, but it is wasteful since you aren't using the object that the system will create with new.

If you want it to be an actual constructor function where you use new and could inherit the prototype, then do this:

functionMake_test(name, job, ID) {
    this.name = name;
    this.job = job;
    this.ID = ID;
}

var o1 = newMake_test("Paul", "manager", 1);
var o2 = newMake_test("John", "employee", 2);
var o3 = newMake_test("Jan", "employee", 2);

Note, I used a capitalized constructor name here since it is a common convention to use initial cap names for constructor functions and initial lowercase names for regular functions.


You could also just remove the declaration entirely:

functionmake_test(name, job, ID) {
    return {name: name, job: job, ID: ID};
}

Or using ES6 syntax:

functionmake_test(name, job, ID) {
    return {name, job, ID};
}

Post a Comment for "Dynamically Access Function Object Property"