Bookshelf.js 文档有带有“new”和没有“new”的代码示例:
在这里http://bookshelfjs.org/#Model-instance-hasMany
let Author = bookshelf.Model.extend({
tableName: 'authors',
books: function() {
return this.hasMany(Book);
}
});
// select * from `authors` where id = 1
// select * from `books` where author_id = 1
Author.where({id: 1}).fetch({withRelated: ['books']}).then(function(author) {
console.log(JSON.stringify(author.related('books')));
});
但是在这里http://bookshelfjs.org/#Model-instance-fetch
let Book = bookshelf.Model.extend({
tableName: 'books',
editions: function() {
return this.hasMany(Edition);
},
chapters: function{
return this.hasMany(Chapter);
},
genre: function() {
return this.belongsTo(Genre);
}
})
new Book({'ISBN-13': '9780440180296'}).fetch({
withRelated: [
'genre', 'editions',
{ chapters: function(query) { query.orderBy('chapter_number'); }}
]
}).then(function(book) {
console.log(book.related('genre').toJSON());
console.log(book.related('editions').toJSON());
console.log(book.toJSON());
});
那么有什么区别呢?
最佳答案
没有区别。
Model.fetch
、Model.query
、Model.where
和 Model.fetchAll
是以下内容的简写:
Model[method] = function(...args) {
return Model.forge()[method](...args);
}
而Model.forge
是new
的简写。
Model.forge = function(...args) {
return new this.constructor(...args);
}
关于javascript - 获取 Bookshelf.js 模型时使用 "new"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635271/