为什么改变原型不会影响之前创建的对象? [英] Why changing the prototype does not affect previously created objects?

查看:45
本文介绍了为什么改变原型不会影响之前创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

var A = function() {};
var a = new A();
var b = new A();
A.prototype.member1 = 10;

A.prototype = {}
var c = new A();
console.log(a.member1);
console.log(a.constructor === b.constructor);
console.log(a.constructor === c.constructor);
console.log('---------');
console.log(c.member1);

它的输出是:

10
true
false
---------
undefined
undefined

ab 的原型没有改变,c 有了新的原型.我是否正确地认为这是由 a.constructor 不等于 c.constructor 并且他们每个人都有自己的 prototype 造成的?当两个对象的构造函数可能不相等时,是否还有其他循环?

The prototype of a and b has not changed and c had a new one. Am i right that this was caused by the fact that a.constructor is not equal to c.constructor and each of them had own prototype? Are there any other circs when constructors of two objects might not be equal?

额外问题:为什么打印了两个 undefined 字符串?(铬)

Extra question: why there were printed two undefined strings? (Chromium)

推荐答案

在你打电话的时候

var a = new A();

基本上这个任务完成了:

basically this assignment is done:

a.__proto__ = A.prototype;

然后您将 A.prototype 重新分配给一个新对象,因此 c{} 作为其原型.

Then you reassign the A.prototype to a new object, so c gets {} as its prototype.

A.prototype = {};
var c = new A();

然而,这并没有破坏旧的 A.prototype 对象 - a.__proto__ 仍然指向它.

However, this doesn't destroy the old A.prototype object - a.__proto__ is still pointing to it.

这是因为 a.constructor 不等于 c.constructor 并且他们每个人都有自己的原型造成的吗?

Am i right that this was caused by the fact that a.constructor is not equal to c.constructor and each of them had own prototype?

.constructor 基本上只是一个方便的属性.它对实例的行为方式没有影响.

.constructor is basically just a convenience property. It has no effect on how instances behave.

额外问题:为什么打印了两个未定义的字符串?

Extra question: why there were printed two undefined strings?

不在我的控制台中,他们没有!(歌剧 12)

Not in my console, they don't! (Opera 12)

这篇关于为什么改变原型不会影响之前创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆