最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

constructor - JavaScript better way to modify function prototype - Stack Overflow

programmeradmin2浏览0评论

I wish to create a constructor of constructors. Relating to this thread : JavaScript build a constructor of constructors, it seems the only solutions are :

Function.prototype.add = function(name, value) {
    this.prototype[name] = value;
};
Function.prototype.remove = function(name) {
    delete this.prototype[name];
};

But I don't want to modify the generic Function prototype... and also :

var A = new ConstBuilder().add('test', function() {
    console.log('test');
}).getConstructor();

But I don't want to have an object wrapper around the constructor itself.

The problem is that generally constructors creates new objects, inheriting methods from the constructor prototype. What I'm trying to do is to instanciates functions instead of objects, but the only way to modify a function prototype property is this to modify its __proto__ property :

var constructorPrototype = {
    add : function(name, value) {
        this.prototype[name] = value ;
    }
} ;

var ConstBuilder = function() {
    var constructor = function() {} ;
    constructor.prototype = {} ;
    // The only way (?), but quite deprecated...
    constructor.__proto__ = constructorPrototype ;
    return constructor ;
} ;

// Not working way...
//ConstBuilder.prototype = constructorPrototype ;

var A = new ConstBuilder() ;
A.add('test', function() {
    console.log('test') ;
}) ;

var a = new A() ;
a.test() ; // "test"

constructorPrototype.remove : function() {
    delete this.prototype[name] ;
} ;

A.remove('test') ;

a.test() ; // Error: test is not a function.

Note that A.prototype is not A.__proto__ but A.prototype is (new A).__proto__.

And it works perfectly by modifying __proto__, what a shame. I read that Firefox has integrated a "Object.setPrototypeOf()" but it is only experimental.

Would it be another way to do what I wish to do ?

I wish to create a constructor of constructors. Relating to this thread : JavaScript build a constructor of constructors, it seems the only solutions are :

Function.prototype.add = function(name, value) {
    this.prototype[name] = value;
};
Function.prototype.remove = function(name) {
    delete this.prototype[name];
};

But I don't want to modify the generic Function prototype... and also :

var A = new ConstBuilder().add('test', function() {
    console.log('test');
}).getConstructor();

But I don't want to have an object wrapper around the constructor itself.

The problem is that generally constructors creates new objects, inheriting methods from the constructor prototype. What I'm trying to do is to instanciates functions instead of objects, but the only way to modify a function prototype property is this to modify its __proto__ property :

var constructorPrototype = {
    add : function(name, value) {
        this.prototype[name] = value ;
    }
} ;

var ConstBuilder = function() {
    var constructor = function() {} ;
    constructor.prototype = {} ;
    // The only way (?), but quite deprecated...
    constructor.__proto__ = constructorPrototype ;
    return constructor ;
} ;

// Not working way...
//ConstBuilder.prototype = constructorPrototype ;

var A = new ConstBuilder() ;
A.add('test', function() {
    console.log('test') ;
}) ;

var a = new A() ;
a.test() ; // "test"

constructorPrototype.remove : function() {
    delete this.prototype[name] ;
} ;

A.remove('test') ;

a.test() ; // Error: test is not a function.

Note that A.prototype is not A.__proto__ but A.prototype is (new A).__proto__.

And it works perfectly by modifying __proto__, what a shame. I read that Firefox has integrated a "Object.setPrototypeOf()" but it is only experimental.

Would it be another way to do what I wish to do ?

Share Improve this question edited May 23, 2017 at 10:32 CommunityBot 11 silver badge asked Feb 14, 2014 at 19:41 TotTot 9153 gold badges13 silver badges30 bronze badges 4
  • a.constructor.prototype==a.__proto__, unless you break the link.does that help your cross-browser implementation? – dandavis Commented Feb 14, 2014 at 19:46
  • It is not a.__proto that I'm modifying, it's A.__proto__ which is a function and is not an instance of ConstBuilder, as ConstBuilder returns it directly instead of returning its new instance. – Tot Commented Feb 14, 2014 at 19:56
  • sorry, i didn't notice you used "a" in your code; i was speaking broadly. so, X.constructor.prototype==X.__proto__ – dandavis Commented Feb 14, 2014 at 21:53
  • I tried constructor.constructor.prototype = constructorPrototype ; but it doesn't work either. :\ – Tot Commented Feb 14, 2014 at 22:26
Add a comment  | 

1 Answer 1

Reset to default 17

Indeed. The only way to do what you wish to do is to mutate the __proto__ property of the function you are returning. However that is not a bad thing. In fact ES6 Harmony is going to standardize it as the Object.setPrototypeOf function.

I would however advise you against mutating the [[Prototype]] of an object because it makes your program very slow. There is a faster alternative available:

Don't Use the Prototype

Traditionally the prototype is used to define functions that operate on a certain type of object. These functions, which specialize on a certain argument, are called methods.

For example, obj.func(a, b, c) specializes on obj and the instances of obj. On the other hand func(obj, a, b, c) doesn't specialize on any argument (i.e. obj can be any value).

Following this example you could rewrite add and remove as follows:

function add(func, name, value) {
    func.prototype[name] = value;
}

function remove(func, name) {
    delete func.prototype[name];
}

Now you can use add and remove on any function you want. You don't have to worry about inheritance at all.

The only problem is namespace conflicts. Suppose you already have a function named add: what do you do? The answer is pretty simple. You create a new namespace:

Function.add = function (func, name, value) {
    func.prototype[name] = value;
};

Function.remove = function remove(func, name) {
    delete func.prototype[name];
};

In fact this is exactly what native JavaScript APIs usually do. For example:

  1. Object.create
  2. Object.getPrototypeOf
  3. Object.setPrototypeOf

So on and so forth.

The point is this: generalization is always better than specialization. We use prototypes to specialize. We use normal functions to generalize. There are a lot of advantages of generalization over specialization:

  1. You don't need methods like call and apply to "unspecialize" specialized functions.
  2. You don't have to worry about inheritance and prototype chains.
  3. Your code is cleaner and easier to understand.

This is the reason I always prefer generalization over specialization. The only reason I ever use prototypes is to created union types. For example:

function Shape(constructor) {
    this.constructor = constructor;
}

function Circle(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
}

function Rectangle(x1, y1, x2, y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
}

Circle.prototype = new Shape(Circle);
Rectangle.prototype = new Shape(Rectangle);

Instead of adding methods to Circle.prototype and Rectangle.prototype I do the following instead:

Circle.area = function (circle) {
  return Math.PI * circle.r * circle.r;
};

Rectangle.area = function (rectangle) {
  return Math.abs((rectangle.x2 - rectangle.x1) * (rectangle.y2 - rectangle.y1));
};

Shape.prototype.area = function () {
  return this.constructor.area(this);
};

Now you can use Circle.area(notCircleInstance) instead of Circle.prototype.area.call(notCircleInstance). It's a win-win situation. Generalization is always better than specialization.

发布评论

评论列表(0)

  1. 暂无评论