简体   繁体   中英

Can anyone help explain “get: function()” and .prototype to me?

I am attempting to build my own JavaScript library using Andrew Burgess' online tutorial ( http://code.tutsplus.com/tutorials/build-your-first-javascript-library--net-26796 ) and am following it fine, but I would like to know what the get: function(selector) does in the following code:

(function() {
function Dyn(elems) {
    for (var i; i < elems.length; i++) {
        this[i] = elems[i];
    }
    this.length = elems.length;
}

var DynamicScript = {
    /*here it is!-->*/get: function(selector) {
        var elems;
        if (typeof selector === "string") {
            elems = document.querySelectorAll(selector);
        } else if (selector.length) {
            elems = selector;
        } else {
            elems = [selector];
        }
        return new Dyn(elems);
    }
};

return DynamicScript;
}());

If anyone could tell me what it does I would be extremely grateful.

Also, in the tutorial, there is a function that looks like this:

Dyn.prototype.map = function (callback) {
var results = [], i = 0;
for ( ; i < this.length; i++) {
    results.push(callback.call(this, this[i], i));
}
return results;
};

I would really like a nice, simple explanation of what .prototype does. I haven't been able to understand what I have already come across about it, so if you could pretend you are talking to an idiot (not too much point in pretending) and explain it in the simplest terms possible I would appreciate it greatly.

Thanks for paying attention, I really do need the help.

Okay!

So, when I asked this question I was a JavaScript newbie, and woefully unaware of objects!

Now that I know what an object is though, I recognise the syntax within the code and am able to understand what it means!

var DynamicScript = {
  get: function(){ 
    ...

Is just creating a property, get, with value function(){... .

Dyn.prototype.map = function (callback) {

Does almost exactly the same thing, creates a property for Dyn called map, with a value of that function.

Ta-da!

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