gpt4 book ai didi

javascript - Class.prototype.method 与 this.prototype.method

转载 作者:行者123 更新时间:2023-12-02 23:14:04 24 4
gpt4 key购买 nike

我总是看到 Class.prototype.method 的示例,但从未见过 this.prototype.method 的实例。例如:

function Class() {
this.prototype.method = function() {
alert("is this allowed?");
};
}

对比

function Class() {}
Class.prototype.method = function() {
alert("traditional example");
};
  1. this.prototype 存在吗?
  2. 和Class.prototype一样吗?
  3. 继承怎么样?

最佳答案

  1. this.prototype 存在吗?

    没有。但是,this.constructor.prototype 应该。

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

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

  3. 继承怎么样?

    每个新类实例都将从Class.prototype继承。因此,原型(prototype)对象非常适合定义所有实例都可以访问的共享值。然后,构造函数只需设置每个实例唯一的状态。

    但是,尝试混合这两种方法并在构造函数中设置 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"

    并且破坏了拥有原型(prototype)的一些好处,因为每个附加实例都会重新创建该方法:

    var method = a.method;

    console.log(a.method === method); // true

    var b = new Class();

    console.log(a.method === method); // false

关于javascript - Class.prototype.method 与 this.prototype.method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com