var vs this in Javascript object

后端 未结 4 743
[愿得一人]
[愿得一人] 2020-11-29 09:33

I\'m developing a web framework for node.js. here is the code;

function Router(request, response) {
        this.routes = {};

        var parse = require(         


        
4条回答
  •  甜味超标
    2020-11-29 10:20

    Using var in the constructor is usually used for private variable while using this. is used for public variable.

    Example with this. :

    function Router() {
        this.foo = "bar";
    
        this.foobar = function () {
             return this.foo;
        }
    }
    
    var r = new Router();
    r.foo // Accessible
    

    Example with var :

    function Router() {
        var _foo = "bar";
    
        this.foobar = function () {
             return _foo;
        }
    }
    
    var r = new Router();
    r._foo // Not accessible
    

提交回复
热议问题