简体   繁体   中英

Attempting to 'encapsulate' reusable javascript code

This whole question is a sort of 'what I've tried' in an attempt to encapsulate my js, but it's not working as I'd hope.

On my page I have a div.

<div id='myDiv'></div>

I also have some script:

<script type="text/javascript">

  $(function () {
    $('#myDiv').hide();
  });

</script>

This script will grow in size and complexity, so I want it off the page and into an external js file. That's fine, but I also want it to be reusable. What the javascript will do is turn a div (and it's children) into a control (slider for example).

So after researching ways in which I can almost mimic oop principles in javascript, I've got the following in an external file:

var MyControl = function () {
    this.init= function (myDiv) { 
        myDiv.hide();
    };
};

I then call it like so:

$(function () {
    var myControl = new MyControl();
    myControl.init($('#myDiv'));
});

The problem is that the div isn't hidden despite calling hide() on it. If I debug this, I see I have the div, it's passed in fine, and hits every line of code I'd expect it to (can even display the div's type in an alert).

Why isn't the div affected on the page?

Is this approach a recommended one for solving the problem I discussed at the start of this post?

If you want use that same div all over time you can try create your component in that way:

function MyControl (div) {
   this.div = div;
}

MyControl.prototype.init = function () {
   return this.div.hide();
}

And use it in this way:

var myControl = new MyControl($('#myDiv'));
myControl.init();

Working fiddle here: http://jsfiddle.net/Z7vRq/

But if you want it to be used only in init function try this way:

function MyControl () { }

MyControl.prototype.init = function (div) {
   return div.hide();
}

var myControl = new MyControl();
myControl.init($('#myDiv'));

Working fiddle here: http://jsfiddle.net/Z7vRq/1/

Regarding to comment:

You can try wrap all construction code into that structure:

var MyControl = (function () {
    function MyControl (div) {
        this.div = div;
    }

    MyControl.prototype.init = function () {
        return this.div.hide();
    }

    return MyControl;

})()

Is this approach a recommended one for solving the problem I discussed at the start of this post?

I would recommend reading the RequireJS " Why Modules " and " Why Asynchronous Module Definitions " articles for a primer on the different challenges and solutions for making modular JavaScript.

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