js 原型 constructor 的困惑

2019-06-24 23:17:27 +08:00
 lbfeng
function Foo(name) {
	this.name = name;
}

Foo.prototype.myName = function() {
	return this.name;
};

function Bar(name,label) {
	Foo.call( this, name );
	this.label = label;
}

console.log(Bar.prototype.constructor);

Bar.prototype = Object.create( Foo.prototype );

console.log(Bar.prototype.constructor);

Bar.prototype.myLabel = function() {
	return this.label;
};

var a = new Bar( "a", "obj a" );

a.myName(); // "a"
a.myLabel(); // "obj a"
console.log(a.constructor);"

第 1 次输出 Bar.prototype 的 constructor 指向 Bar 完全可以理解。 function Bar(name,label){Foo.call(this,name);this.label=label;}

第 2, 3 次输出 Bar.prototype 的 constructor 指向 Foo 也完全可以理解。 function Foo(name){this.name=name;} function Foo(name){this.name=name;}

如果 new Bar 有用到 Bar.prototype.constructor 的话 label 是怎么放入 a 的? 要是没用到的话 constructor 有什么意义?

画了个图帮助理解 i.imgur。com/k5LMrEV.jpg

3012 次点击
所在节点    JavaScript
6 条回复
lbfeng
2019-06-24 23:24:56 +08:00
imgur。com/a/dQZ821s
connection
2019-06-25 00:24:59 +08:00
Bar.prototype = Object.create( Foo.prototype );

访问 a 实例的时候访问 constructor 实际上在访问 Foo.prototype 上的 constructor 了吧
lbfeng
2019-06-25 04:42:41 +08:00
@connection 是的,第二个输出证明这点。
azh7138m
2019-07-09 15:46:35 +08:00
> label 是怎么放入 a

不是你自己写的吗?
function Bar(name,label) {
Foo.call( this, name );
this.label = label;
}

this.label = label;
lbfeng
2019-07-10 00:32:24 +08:00
@azh7138m 第 4 次输出没写全。a.constructor 是 Foo 而不是 Bar. 这才是我要问的问题。是 Bar 的话我就不用问了。。。
lbfeng
2019-07-19 05:42:29 +08:00
我自己终结吧。var a = new Bar(…)。这个和 new 的过程有关。

1. Create a new empty object.
2. Assign the “ this ” value of the constructor function to the new empty object (so this points to the new object).
3. Execute the code inside the constructor function (adds properties to the new object).
4. Return the new object if constructor function doesn ’ t have a explicit return statement.

所以整个创建过程和 prototype.constructor 没啥关系。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/577072

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX