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?

4

1 回答 1

3

您正在调用this.setFunction();您的初始init. 每当您调用构造函数时都会遇到这种情况。

因此,它会被两者击中两次:

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

然后你再次单独调用它,以获得第三次:

f1.setFunction();  
于 2013-10-09T15:48:51.893 回答