首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >function.constructor对function.prototype.constructor

function.constructor对function.prototype.constructor
EN

Stack Overflow用户
提问于 2021-06-22 19:54:37
回答 1查看 80关注 0票数 0

我已经准备了相当多的博客文章和堆叠溢出的问题,但不能很好地理解这一点。

Why is it necessary to set the prototype constructor?

Trying to understand the difference between prototype and constructor in JavaScript

Constructors in JavaScript objects

JavaScript inheritance and the constructor property

Understanding the difference between Object.create() and new SomeFunction()

问题

代码语言:javascript
复制
function person(fname) {
  this.fname = fname;
}

let obj1 = new person('first'); //works well
console.log(obj1);
let obj2 = new person.prototype.constructor('second'); //works well
console.log(obj2);
//now the query
console.log(person.constructor); //1. it prints  function Function() { [native code] } what does it mean
let obj3 = new person.constructor('third') // 2. why this doesn't work ?
console.log(obj3); //

现在,我们知道javascript中的每个函数都有一个属性调用prototype,它是一个object,它有一个名为constructor的属性,它指向原型对象是属性的函数。-如果我做错了这件事,纠正我

因此,根据上述声明,person.prototype.constructor === person (两者是相同的)

查询: 1 person.constructor打印function Function() { [native code] }是什么意思,请详细解释。

查询: 2为什么这个new person.constructor('randon')不能工作?

查询: 3,person.constructor到底是什么,它与person.prototype.constructor有什么不同?

EN

回答 1

Stack Overflow用户

发布于 2021-06-22 20:16:49

大致如下:

  1. 函数构造函数是由JS引擎实现的,您使用的引擎在本机代码中实现了它(也许它们都实现了)。

  1. 定义了"works";它创建了一个新函数(参见#1),其中的字符串作为它的主体,如果运行返回的函数,它就会爆炸。如果传入一个有效的函数体,它可以很好地工作,例如

代码语言:javascript
复制
> let obj3 = new person.constructor("console.log('hi')")
> obj3()
hi

  1. #1和#2回答这个问题。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68090019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档