简体   繁体   中英

javascript node.js unexpected token . error

I'm trying to run the next code with 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);

this is the file, let's call it file.js. What I want to do is add method to the prototype of function so that i'm able to add a method with a name and a function. This way I can hide the prototype in other parts of my code. I got this code from a book called: "Javascript the good parts"

 $ node file.js

Gives me the error:

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 .

The function constructor is Function (capital F ), not function . The latter is a keyword. The prototype for functions is Function.prototype .


Once you've fixed that, you'll also need to fix:

function.method('new', ...

I don't know what you're trying to do there. If you're trying to add a method to the prototype attached to a constructor function, you'd need to use the actual function's name there, eg:

function Thingy() {
    // I make Thingy object
}
Thingy.method('new', ...

(But using a keyword like new for a method name, while valid in ES5, is a Really Bad Idea.)

You should use Function not function .

Function is the constructor used to create new function objects. Consequently, the prototype for function objects is Function.prototype .

function is a keyword used to declare a function statement or expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM