[英]javascript node.js unexpected token . error
我正在尝试使用node.js运行下一个代码:
1 //Add a method conditionally
2
3 function.prototype.method = function (name, func) {
4 if (!this.prototype[name]) {
5 this.prototype[name] = func;
6 return this;
7 }
8 };
9
10
11 function.method('new', function ( ) {
12
13 // Create a new object that inherits from the
14 // constructor's prototype.
15 var that = Object.create(this.prototype);
16 // Invoke the constructor, binding -this- to
17 // the new object.
18 var other = this.apply(that, arguments);
19 // If its return value isn't an object,
20 // substitute the new object.
21 return (typeof other === 'object' && other) || that;
22 });
23
24 var Mammel = function(name) {
25 this.name=name;
26 };
27
28 Mammel.prototype.get_name = function() {
29 return this.name;
30 };
31
32 Mammel.prototype.says = function() {
33 return this.saying || '';
34 };
35
36 var myMammel = new Mammel('Herbdiderp');
37 var name = myMammel.get_name();
38
39 console.log(name);
这是文件,我们称它为file.js。 我想做的就是将方法添加到函数原型中,这样我就可以添加带有名称和函数的方法。 这样,我可以将原型隐藏在代码的其他部分。 我从一本书中获得了这段代码:“ Javascript的优点”
$ node file.js
给我错误:
Desktop/file.js:3
function.prototype.method = function (name, func) {
^
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token .
函数构造函数是Function
(大写F
),而不是function
。 后者是关键字。 函数的原型是Function.prototype
。
修复此问题后,还需要修复:
function.method('new', ...
我不知道您要在那做什么。 如果要向附加到构造函数的原型添加方法,则需要在此处使用实际函数的名称,例如:
function Thingy() {
// I make Thingy object
}
Thingy.method('new', ...
(但是在方法名称中使用诸如new
类的关键字,虽然在ES5中有效,但这是一个糟糕的主意。)
您应该使用Function
not function
。
Function
是用于创建新功能对象的构造函数。 因此,功能对象的原型为Function.prototype
。
function
是用于声明函数语句或表达式的关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.