Prototype Property for Function

I am trying to do this:

a = new Foo(name); // a is function
a(); // returns a result
a.set(); // returns another result

I implemented above:

function Foo (name) = {
  val = name;
  ret = function () { return val; }
  ret.set = function (v) { return val = v; }
  return ret;
}

Then, for multiple instances of Foo, I would like not to create the 'set' method, but to share it through the prototype property. However, all the experiments I did had no effect. It only works on objects, not functions. Even the code below does not work:

foo = function () { return 'a'; }
foo.foo = function ()  { return 'foo'; }
foo.prototype.bar = function ()  { return 'bar'; }

foo(); // a
foo.foo(); // foo
foo.bar(); // Uncaught TypeError: Object function () { return 'a'; } has no method 'bar' 
+4
source share
3 answers

Unfortunately, there is no way to add a property to only certain functions through a prototype chain. Functions have one object in the prototype chain, which is equal Function.prototype. It is not possible to create functions that have other [[Prototype]]s.

, , :

function Foo (name) = {
  val = name;
  ret = function () { return val; }
  ret.set = function (v) { return val = v; }
  return ret;
}

. prototype

Function.prototype.set = function (v) { return this.val = v; };
function Foo (name){
  ret = function () { return this.val; }
  ret.val = name;
  return ret;
}

var f = new Foo('myfunc');
f.set('myval');
console.log(f.val);

, , / set. Prototypes , .

+1

foo bar, .

, foo bar


, :

foo = function () { return 'a'; }
foo.foo = function ()  { return 'foo'; }
foo.prototype.bar = function ()  { return 'bar'; }

var f = new foo(); // [object]
f.foo(); // TypeError: Object [object Object] has no method 'foo'
f.bar(); // bar
0

:

foo = function (name){
      this.name = name;
    }
foo.prototype.set = function(name){ return this.name = name; }

var f = new foo('yourName');
alert(f.name);
f.set('yourNameEdited');
alert(f.name);

DEMO

0

All Articles