简体   繁体   中英

Read properties and call methods from another object Javascript Prototype Pattern

Im trying to get how can I access properties from another constructor. I want to separate objects like App, Effects, Utils for example and call properties and methods from one to another. Is that possible, or is this way completely wrong way?

var App = function() {

    this.someProperty = 'Lorem';
    this.init();
};

App.prototype = {

    init:function(){
        this.bindEvents();
    },

    bindEvents:function(){

        var self = this;

        $(window).on('resize', function(e) {
            e.preventDefault();
            this.windowWidth = $(window).width();
            // Is that Correct?
            Utils.prototype.resizeElement(this.windowWidth);
        });

    }

};


var Utils = function(){};


Utils.prototype = {

    resizeElement: function(windowW){
        console.log(windowW);   
    },

    someMethod:function(){

        // How can i access property written in App constructor?
        console.log(this.someProperty);
    }

};


var Effects = function(){
    this.init();
};


Effects.prototype = {

    hideElement:function(ele){
        $(ele).hide();
    }

};


var app = new App();

When you have classes, the classes themselves don't serve for much. Instances of classes are what you want. So calling Utils.resizeElement from App wouldn't do anything, as resizeElement is a part of the prototype (ie part of what an instance gets, not what the class itself gets).

You need to decide if you're grouping methods and concepts into a single-instance, in which case you could just use a JS object, such as:

var Utils = {
  resizeElement: function(window) { ... }
}

If you had an object called Utils that had a method property called resizeElement then you could call it from App with Utils.resizeElement .

If you truly want a class, then you have two choices: 1) pass an instance of a Utils to your App or create a new instance inside App .

Option 1:

var App = function(utils) {
    this.utils = utils;
    this.someProperty = 'Lorem';
    this.init();
};

App.prototype = {

    init: function(){
        this.bindEvents();
        this.utils.resizeElement(...);
    }
}

var u = new Utils();
var a = new App(u);

Or do it internally

var App = function() {
    this.utils = new Utils();
    this.someProperty = 'Lorem';
    this.init();
};

App.prototype = {

    init: function(){
        this.bindEvents();
        this.utils.resizeElement(...);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM