0

I created a skeleton of a javascript function with prototype:

'use strict';  
var functionName = (function () {  
    var functionName = function(param1){  
        console.log("functionName " + param1);  
        this.init(param1);  
    };  

    // public function  
    functionName.prototype = {  
        init : function(param1) {  
            console.log("init " + param1);  
            var privateVar = param1;  
            this.setFunction();  
        },  
        setFunction : function() {  
            console.log("setFunction");  
            // do stuff here  

        }  
    };  

    return functionName;  
}());  

// Instances creation  
var f1 = new functionName("f1");  
var f2 = new functionName("f2");  
f1.setFunction();  
console.log("private var : " + f1.privateVar);  

See the code in here What do you think? Here is the log of this script:

functionName f1 (index):25  
init f1 (index):32  
setFunction (index):37  
functionName f2 (index):25  
init f2 (index):32  
setFunction (index):37  
setFunction (index):37  
private var : undefined (index):51  

I don't understand why I saw three times setFunction. Does someone have an idea?
The prototype of the function SetFunction should not be executed once?

1 Answer 1

3

You are invoking this.setFunction(); within your initial init. This is being hit whenever you invoke your constructor.

Therefore, it gets hit twice with both:

var f1 = new functionName("f1");  
var f2 = new functionName("f2");

Then you are separately calling it again, to get the third time:

f1.setFunction();  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.