Class.prototype.method vs this.prototype.method

005*_*005 22 javascript prototype

我一直看到Class.prototype.method的例子,但从来没有看过this.prototype.method的例子.例如:

function Class() {
    this.prototype.method = function() {
        alert("is this allowed?");
    };
}
Run Code Online (Sandbox Code Playgroud)

VS

function Class() {}
Class.prototype.method = function() {
    alert("traditional example");
};
Run Code Online (Sandbox Code Playgroud)
  1. this.prototype存在吗?
  2. 它与Class.prototype相同吗?
  3. 继承怎么样?

Jon*_*ski 19

  1. this.prototype存在吗?

    不,但是,this.constructor.prototype应该.

  2. 它与Class(.constructor).prototype相同吗?

    它通常具有相同的值(只要this.constructor === Class),但意图不同.

  3. 继承怎么样?

    每个new Class实例都将继承自Class.prototype.因此,prototype对象适用于定义所有实例都可访问的共享值.然后,构造函数只需设置对每个实例唯一的状态.

    但是,尝试混合2并prototype在构造函数中设置属性有一些问题,包括鸡或蛋冲突,因为在创建第一个实例之前该方法不会存在:

    function Class() {
        this.constructor.prototype.method = function () {};
    }
    
    console.log(typeof Class.prototype.method); // "undefined"
    
    var a = new Class();
    
    console.log(typeof Class.prototype.method); // "function"
    
    Run Code Online (Sandbox Code Playgroud)

    并且失败了prototype使用每个附加实例重建方法的一些好处:

    var method = a.method;
    
    console.log(a.method === method); // true
    
    var b = new Class();
    
    console.log(a.method === method); // false
    
    Run Code Online (Sandbox Code Playgroud)


Vto*_*one 4

this.prototype 将引用该类对象的实例。由于范围的原因,它不会给你带来太多好处。

Class.prototype 正在向类添加功能,而不是向其实例添加功能。