Javascript Prototype not Working

后端 未结 4 452
刺人心
刺人心 2021-01-06 20:59

Hi I don\'t know whether this is my mistake in understanding Javascript prototype object ..

Well to be clear I\'m new to the Javascript singleton concept and lack c

相关标签:
4条回答
  • 2021-01-06 21:13

    Update: Seeing your updated code, the return from referrelSystem won't work as expected, since return values are discarded when calling new referrelSystem().

    Rather than returning an object, set those properties to this (the instance of referrelSystem that gets constructed):

    var referrelSystem = function () {
        // I assume you have other code here
    
        this.login = getSignedIn;
        this.initTwitter = initTw;
    };
    
    0 讨论(0)
  • 2021-01-06 21:26

    A typical way to define a JavaScript class with prototypes would be:

    function ReferrelSystem() {
        // this is your constructor
        // use this.foo = bar to assign properties
    }
    
    ReferrelSystem.prototype.postToFb = function () {
        // this is a class method
    };
    

    You might have been confused with the self-executing function syntax (closures). That is used when you would like to have "private" members in your class. Anything you declare in this closure will only be visible within the closure itself:

    var ReferrelSystem = (function () {
        function doSomething() {
            // this is a "private" function
            // make sure you call it with doSomething.call(this)
            // to be able to access class members
        }
    
        var cnt; // this is a "private" property
    
        function RS() {
            // this is your constructor
        }
    
        RS.prototype.postToFb = function () {
            // this is a class method
        };
    
        return RS;
    })();
    

    I would recommend that you study common module patterns if you're looking into creating a library.

    0 讨论(0)
  • 2021-01-06 21:29

    A function should return to work as

    prototype

    property. Take a look at this example here

    0 讨论(0)
  • 2021-01-06 21:34

    I don't think you intend to immediately execute the functions, change them to this:

    var referrelSystem = function(){
    //Some code here
    };
    

    (+var, -())

    Same with the prototype function:

    referrelSystem.prototype.postToFb = function(){
    //Some Code here
    };
    

    (Here you don't need the var, because you're assigning to something that already exists.)

    0 讨论(0)
提交回复
热议问题