【问题标题】:Set class/prototype variable from jQuery function从 jQuery 函数设置类/原型变量
【发布时间】:2019-01-01 19:37:31
【问题描述】:
有人可以帮助我了解在这种情况下如何将值从 $.each 函数推送到 this.books 数组中吗?
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 );
}
};
谢谢。
【问题讨论】:
标签:
jquery
variables
closures
this
prototype
【解决方案1】:
$.each 是一个 jQuery 函数,它为传递的数组中的每个元素调用封闭的函数。在封闭的函数内部,this 成为对元素的引用,而不再是对 Library 对象的引用。
所以在封闭的函数中,this.books 指向book[index].books,其中index 是数组中元素的索引。
您可以通过设置对库对象的替代引用来解决此问题。
var lib = this;
$.each(book, function(){
console.log($(this));
lib.books.push($(this));
});
或者你可以使用循环代替
for(var i = 0; i < book.length; i++)
{
console.log(book[i]);
this.books.push(book[i]);
}
【解决方案2】:
使用function() 语法定义函数会在函数内部创建一个新范围。这样,当您访问this.books 时,您会尝试从尚未定义的$.each 内部获取this.books。
要解决此问题,请使用内联函数 () => {}。内联函数不会重新定义范围,因此您可以安全地访问 this.books。
如果您在旧版本的 JavaScript 上运行并且无法使用内联函数,则解决方案是将 .bind(this) 放在 $.each 语句中函数定义的末尾。