Set class/prototype variable from jQuery function

时间:2018-07-25 05:10:24

标签: jquery variables closures this prototype

Can somebody help me to understand how in this situation I can push values from $.each function into this.books array?

let Library = function ( name ) {
    this.name = name;
    this.books = Array();
};

Library.prototype.addBook = function ( book ) {
    if( Array.isArray( book ) ) {
        $.each(book, function() {
            console.log($(this));
            this.books.push($(this));
        });
    } else if ( typeof book === 'object' ) {
        this.books.push( book );
    }
};

Thank you.

2 个答案:

答案 0 :(得分:0)

$.each is a jQuery function that calls the enclosed function for every element in the passed array. Inside the enclosed function, this becomes a reference to the element, and is no longer a reference to the Library object.

So inside your enclosed function, this.books points to book[index].books, where index is the index of the element in the array.

You can fix this by setting an alternative reference to the Library object.

var lib = this;
$.each(book, function(){
    console.log($(this));
    lib.books.push($(this));
});

Or you could use a loop instead

for(var i = 0; i < book.length; i++)
{
    console.log(book[i]);
    this.books.push(book[i]);
}

答案 1 :(得分:0)

Defining a function using function() syntax creates a new scope inside the function. That way, when you access this.books you are attempting to get the this.books from inside the $.each which hasn't been defined yet.

To solve this, use an inline function () => {}. Inline functions don't redefine scope and so you can safely access this.books.

If you are running on an older version of JavaScript and cannot use an inline function, then the solution is to put .bind(this) at the end of your function definition inside the $.each statement.