javascript - This scope lost with inheritance -


here example code, 2 files , "classes".

crud class defined methods, problem occurs this.modelname, set routes context changes code:

the question how, same scope under crud have defined modelname ?

server.get('/users/:id', userroutes.find); 

code:

var db = require('../models');  function crud(modelname) {     this.modelname = modelname;     this.db = db; }  crud.prototype = {      ping: function (req, res, next) {         res.json(200, { works: 1 });     },      list: function (req, res, next) {          // fails because modelname undefined         console.log(this);          db[this.modelname].findall()             .success(function (object) {                 res.json(200, object);             })             .fail(function (error) {                 res.json(500, { msg: error });             });     } };  module.exports = crud; 

userroutes class:

var crud = require('../utils/crud'), util = require('util');  var usermodel = function() {     usermodel.super_.apply(this, arguments); };  util.inherits(usermodel, crud);  var userroutes = new usermodel('user');  module.exports = userroutes; 

i assume using userroutes.list handler somewhere else, i.e. context changes. in case should simple solution:

function crud(modelname) {     this.modelname = modelname;     this.db = db;     this.list = crud.prototype.list.bind(this); } 

note won't able access "the other this" solution (this permamently bound crud instance, no matter how .list called).

the other option turn list function generator (which pretty same .bind does, except can still use this other context):

crud.prototype = {     // code      list: function() {         var = this;         return function (req, res, next) {             console.log(that);              db[that.modelname].findall()                 .success(function (object) {                     res.json(200, object);                 })                 .fail(function (error) {                     res.json(500, { msg: error });                 });         }     } }; 

and use userroutes.list() handler.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -