The Difference between Prototype Parameter Transmission and Direct Parameter Transmission

  node.js, question

I don’t know if this is correct.

Code first

user.js

var baseDao = require('../dao/baseDao');
 
 function User(user) {
 this.ID = user.ID || null;
 this.CODE = user.CODE  || null;
 this.NAME = user.NAME  || null;
 bracket
 
 User.prototype = baseDao;
 User.prototype.table_name = 'user';
 
 module.exports = User;

baseDao.js

// Sql builder
 var squel = require('squel');
 // DB ThreadPool
 var pool = require('../tool/DB');
 
 //incorrect usage
 // function save(callback) {
 //    var ob = this;
 function save(ob, callback) {
 var sql = squel.insert()
 .into(table_name)
 .setFields(ob)
 .toString();
 pool.getConnection(function (err, conn) {
 if (err) {
 return callback(err);
 bracket
 conn.query(sql, function (err) {
 conn.release();
 if (err) {
 return callback(err);
 bracket
 callback(null)
 });
 });
 bracket
 ...

route.js

...
 var User = require('../src/user');
 ...
 router.post('/profile', function (req, res, next) {
 var user = JSON.parse(req.body.user);
 // save
 var _user = new User(user);
 _user.save(user, function (err) {
 ...
 })
 });

Call relationrouter.js->user.js->baseDao.js

squel.jsIt’s a package.mysqlDriver module.

The problem lies in.setFields(ob)This place, error message

Error: field value must be a string, number, boolean, null or one of the registered custom value types

The official document gives the following usage:

squel.insert()
 .into("students")
 .setFields({ name: "Thomas", age: 29 })
 .toString()

I think there is no problem with my call

The two call methods arebaseDao.jsIs used in the save method ofJSON.stringify()The printed objects are identical.

However, if you use it directly (the part that has been commented out is the case of error reporting), this will report an error, and if you pass it directly to ob object, it will not report an error.

There must be something wrong, please correct me!

The reason is.setFieldsThe method traverses the passed-in attributes. Due to the role of the prototype chain, some irrelevant attributes are also traversed. For example, the baseDao.save method, JSON.stringify can only detect two objects themselves, and references on the prototype chain are not considered.

Let’s just use JSON.stringify and then parse back to solve it