javascript - 从构造函数中将方法附加到原型(prototype)

标签 javascript prototypal-inheritance

这是描述 JavaScript 中“类”或构造函数的教科书标准方法,直接来自 JavaScript 权威指南:

function Rectangle(w,h) {
    this.width = w;
    this.height = h;
}
Rectangle.prototype.area = function() { 
    return this.width * this.height;
};

我不喜欢这里的悬空原型(prototype)操作,所以我试图想办法将 area 的函数定义封装在构造函数中。我想到了这个,但我期望它能工作:

function Rectangle(w,h) {
    this.width = w;
    this.height = h;
    this.constructor.prototype.area = function() { 
        return this.width * this.height;
    };
}

我没想到这会起作用,因为 area 函数中的 this 引用应该指向 area 函数本身,所以我无法从 this 访问 widthheight。但事实证明我知道!

var rect = new Rectangle(2,3);
var area = rect.area(); // great scott! it is 6

一些进一步的测试证实 area 函数中的 this 引用实际上是对 正在构建的对象 的引用,而不是 area 函数本身。

function Rectangle(w,h) {
    this.width = w;
    this.height = h;
    var me = this;
    this.constructor.prototype.whatever = function() { 
        if (this === me) { alert ('this is not what you think');}
    };
}

结果提示弹出,this 正是正在构建的对象。那么这里发生了什么?为什么 this 不是我期望的 this

最佳答案

我认为正确的答案是你不应该这样做,因为正如 kennebec 在评论中所说:

If you have a hundred rectangles, you are going to redeclare that prototype method a hundred times.

关于javascript - 从构造函数中将方法附加到原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429059/

相关文章:

javascript - 多页面环境下的PHP和JS

带有原型(prototype)的 Javascript 函数继承

javascript - javascript中的原型(prototype)继承概念作为基于原型(prototype)的语言

javascript - ES6 类构造函数不能作为普通函数调用的原因是什么?

Javascript 继承 - Ctor 参数和重写函数

javascript - React Native this2 .'function' 不是函数

javascript - 需要帮助使事件处理程序在 React js 中正常工作

javascript - Object.create 中的对象属性值是常量吗?

javascript - 这个javascript模式可以吗?

javascript - 创建一个 javascript 库闭包