简体   繁体   中英

JavaScript Object Conundrum

I'm trying to improve my terrible JavaScript skills by using objects rather than just getting by with globals and random sets of functions. My PHP framework until now used two files for any given (set of) page(s)... functions.js and ajax.js . I want to keep the separation, but use objects to achieve the same result.

If I have an object...

var testJS = {

    init: function(options) {
        var defaultSettings = {
            someOption: false,
            fadeLogo: false
        },

        settings = $.extend({}, this.defaultSettings, options),

        base = this;

        // call ajax function...
        ajax.doSomething();

    },

    somethingElse: function() {
        // whatever
    }
});

$(document).ready(function() {
    testJS.init();
});

And then I create an ajax object...

var ajax = {
    doSomething: function(some_var) {
        $.post("Ajax.class.php", {"mode": 'doSomething', 'some_var': some_var}, function(data) {
            something = $.parseJSON(data);
            $('#someId').html(something);

            // call somethingElse function from testJS

        });
    }
}

My question seems really dumb...

How do I call (if I can) the somethingElse function from the ajax object? It seems like it should be available.

由于您只有一个对象实例,因此您只需使用包含该实例的全局变量:

testJS.somethingElse();

I think you want to create a new class , not just an object. Then you could build a new testJS object inside your ajax callback.

function testJS() {
        this.init = function(options) {
            var defaultSettings = {
                    someOption: false,
                    fadeLogo: false
            };

            this.settings = $.extend({}, this.defaultSettings, options);

            var base = this;

            // call ajax function...
            ajax.doSomething();

        };

        this.somethingElse = function() {
            // whatever
        };
}

Then, inside the ajax callback:

var myTestJS = new testJS({ /* Your options here */ });
myTestJS.somethingElse();

I like this better than the other answer because, while the constructor for this object is still global, the object itself only exists inside the scope of the callback. If you want the global behavior, you can still use this method. Just call the constructor outside the callback.

Edit

The way I defined the init function above, your base variable isn't going to be able to do anything. I should declare it like this:

function testJS() {
    var base = this;
    ...

And then remove the var base = this; line inside init . Sorry about that.

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