MeisterAbababa
MeisterAbababa

Reputation: 176

Function as a prototype's objects's property in Javascript?

I have a code similar to this:

var thing = function (prop1, prop2, prop3) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
};

function assignProp1 () {
    return 'value1'; //Function simplified for the question
}

function generateThing () {
    return new thing(function () {return assignProp1();}, 'value2', 'value3'); 
}

What I want to do is create different objects from the protoype "thing". But the code, instead of accepting 'value1' as prop1, returns "generateThing/<()" as prop1. I don't understand why it doesn´t work.

Upvotes: 0

Views: 60

Answers (2)

skazska
skazska

Reputation: 421

If you try to generate object where prop1 is a function, returning "value1" your code should work fine. If you want object with prop1 = "value1" - first answer is good to you

Now if you add

thing1 = generateThing();
console.log(thing1.prop1());

you will see a "value1" in console

here is a snippet:

var thing = function (prop1, prop2, prop3) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
};

function assignProp1 () {
    return 'value1'; //Function simplified for the question
}

function generateThing () {
    return new thing(function () {return assignProp1();}, 'value2', 'value3'); 
}

thing1 = generateThing()

$("#out").text(thing1.prop1())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<span id="out"> </out>

Upvotes: 0

Simone
Simone

Reputation: 81

var thing = function (prop1, prop2, prop3) {
    this.prop1 = prop1;
    this.prop2 = prop2;
    this.prop3 = prop3;
};

function assignProp1 () {
    return 'value1'; //Function simplified for the question
}

function generateThing () {
    return new thing( assignProp1(), 'value2', 'value3'); 
}

Upvotes: 1

Related Questions