问个关于N-blog中一个问题。
N-blog中取数据是User.get方法,但我改用User.prototype.get就报错了(用User.get是正常的),一下子不懂了。
Express
500 TypeError: Object function User(user) {
this.name = user.name;
this.password = user.password;
this.email = user.email;
} has no method 'get'
this.name = user.name;
this.password = user.password;
this.email = user.email;
} has no method 'get'
at /Users/shidoudou/Documents/dev1/node/blog/routes/index.js:33:14
at callbacks (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/lib/router/index.js:164:37)
at param (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/lib/router/index.js:33:10)
at next (/Users/shidoudou/Documents/dev1/node/blog/node_modules/express/node_modules/connect/lib/proto.js:169:15)
at /Users/shidoudou/Documents/dev1/node/blog/node_modules/express/node_modules/connect/node_modules/express-session/index.js:314:9
at /Users/shidoudou/Documents/dev1/node/blog/node_modules/connect-mongo/lib/connect-mongo.js:222:17
at /Users/shidoudou/Documents/dev1/node/blog/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/collection/query.js:147:5
2 回复
简单来说prototype是在User的原型中添加方法,User.get是在User对象中添加方法 具体的表现为,如果是在原型中添加的方法,那这个方法需要创建一个User对象才可以调用到,比如
User.prototype.get = function() {
//...do something
}
var newUser = new User();
newUser.get();
如果没有prototype,那么这个方法就是User的方法,可以直接调用,比如
User.get = function() {
//.. do something
}
User.get();
这只是从应用角度简单说了下,建议楼主可以看看JavaScript的面向对象部分,这应该是属于基础的知识~
谢谢,明白了,十分感谢