提问人:Peter Yablochkin 提问时间:7/25/2018 更新时间:7/25/2018 访问量:41
从jQuery函数设置类/原型变量
Set class/prototype variable from jQuery function
问:
有人可以帮我理解在这种情况下如何将值从 $.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 );
}
};
谢谢。
答:
0赞
Liftoff
7/25/2018
#1
$.each
是一个 jQuery 函数,它为传递的数组中的每个元素调用封闭的函数。在封闭的函数中,成为对元素的引用,并且不再是对 Library 对象的引用。this
因此,在封闭的函数中,指向 ,其中是数组中元素的索引。this.books
book[index].books
index
可以通过设置对 Library 对象的替代引用来解决此问题。
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]);
}
0赞
EmandM
7/25/2018
#2
使用语法定义函数会在函数内创建一个新作用域。这样,当您访问时,您正在尝试从尚未定义的内部获取。function()
this.books
this.books
$.each
要解决此问题,请使用 内联函数 。内联函数不会重新定义范围,因此您可以安全地访问 。() => {}
this.books
如果您在旧版本的 JavaScript 上运行并且无法使用内联函数,那么解决方案是将函数定义的末尾放在语句中。.bind(this)
$.each
评论