gpt4 book ai didi

javascript - 获取 Bookshelf.js 模型时使用 "new"有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:27 29 4
gpt4 key购买 nike

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.fetchModel.queryModel.whereModel.fetchAll 是以下内容的简写:

Model[method] = function(...args) {
return Model.forge()[method](...args);
}

Model.forgenew的简写。

Model.forge = function(...args) {
return new this.constructor(...args);
}

关于javascript - 获取 Bookshelf.js 模型时使用 "new"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635271/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com