javascript - function Name.prototype.method Name() 和 fun Object.methodName() 中调用函数有什么区别吗?

标签 javascript node.js

如果我创建一个像这样的函数构造函数

function ClassName() {
}

然后我为这个构造函数编写方法,如下所示

ClassName.prototype.a = function() {
console.log("A Executed")
}

现在我有两种方法来调用这个新创建的方法a

  1. ClassName.prototype.a()
  2. var obj = new 类名() obj.a()

上述两种方式都给了我完全相同的输出,即

A Executed

但在某些地方我觉得这些一定是一些我没有意识到的差异。这两种方式有什么区别吗。请有人照亮

最佳答案

区别在于函数上下文

function ClassName(name) {
  this.name = name;
}

ClassName.prototype.a = function() {
  console.log("A Executed", this.name, this === obj, this === ClassName.prototype)
}

var obj = new ClassName('test')
obj.a();
ClassName.prototype.a()

关于javascript - function Name.prototype.method Name() 和 fun Object.methodName() 中调用函数有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517936/

相关文章:

Node.js:Mongoose initializeUnorderedBulk 返回 null

javascript - 如何在 JavaScript 中对数组进行排序

javascript - jquery选择元素的方法

javascript - Vue ToDo List,点击按钮的Target父数组列表项

node.js - 无法运行 nools

javascript - Electron - TypeError : core. require is not a function

node.js - Firebase 管理员 : Is it necessary to check if uid decoded on the server (based on client ID token) matches the uid from the client?

javascript - Node.js 请求返回 301 重定向

javascript - 使用 React Hooks 卸载组件时如何访问状态?

php - 406 和 404 错误 - 仅 Firefox 有问题?