简体   繁体   English

func.prototype.constructor是否与func完全相同?

[英]Is the func.prototype.constructor exactly same as func?

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

If A===A.prototype.constructor then invoking both of them does not set the name variable on window object If A===A.prototype.constructor则调用它们两者都不会在窗口对象上设置name变量

Only A("abhishek") sets the variable on window and A.prototype.constructor("randommm") does not! 只有A("abhishek")在窗口上设置变量,而A.prototype.constructor("randommm")不会!

Can someone please explain what's the difference, I am thinking that 有人可以解释一下有什么区别吗,我在想

A.prototype.constructor("randommm")

is called from a different context? 是从不同的上下文调用的?

Yes, they run in different contexts. 是的,它们在不同的上下文中运行。

You're creating a hoisted function in the local scope, which means its default context, unless you bind it to something else, will be window (or at any rate the global namespace) when you invoke it. 您正在本地范围内创建一个提升的函数,这意味着除非您将其绑定到其他对象,否则它的默认上下文将在您调用它时成为window (或无论如何是全局名称空间)。

Calling it via prototype.constructor , though, calls it as a method of the prototype object, so it's logical that the prototype is the context. 但是,通过prototype.constructor调用它,将其作为prototype对象的方法来调用,因此逻辑上是原型是上下文。

function A() { alert(this); }
A(); //context = window
A.prototype.constructor(); //context = prototype

Fiddle . 小提琴

Yes: 是:

A()

calls the function with this being window 调用this window的函数

A.prototype.constructor("randommm")

calls the constructor property of A.prototype which is its context. 调用A.prototype的构造函数属性,即它的上下文。

However i don't see the sense of calling a constructor without new ... 但是我看不到没有new的调用构造函数的感觉...

A.prototype.constructor("randommm") is setting the property name on A.prototype : A.prototype.constructor("randommm")A.prototype上设置属性name

 function A(name){ this.name=name; } A.prototype.constructor("John Doe"); console.log(A.prototype.name); // John Doe 

The value of this will be whatever before the . this将是前面什么. in the call to the function (unless, ofcourse, it is explicitly specified using bind ). 在对函数的调用中(当然,除非使用bind显式指定)。

as a side note if you really want to use the constructor instead of function this 作为旁注,如果您真的想使用构造函数而不是函数this

A.prototype.constructor.bind(this)("randommm")

works. 作品。 But I think it doesn't make any sense in this case 但我认为在这种情况下没有任何意义

The function being called is the same in both cases, what changes is the context in which it is being called. 在两种情况下,被调用的函数都相同,所调用的上下文有所不同。

Here the function is called on its own, so it uses global context: 在这里,该函数是单独调用的,因此它使用全局上下文:

A("abhishek") 

Here the function is called on A.prototype, so it uses A.prototype context: 在此,此函数在A.prototype上调用,因此它使用A.prototype上下文:

A.prototype.constructor("randommm")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM