[英]a question about the prototype in javascript
<script>
function ClassA()
{
this.a=function(){alert();};
}
function ClassB()
{
this.b=function(){alert();};
}
ClassB.prototype=new ClassA();
var objB1=new ClassB();
var objB2=new ClassB();
alert(objB1.a==objB2.a);
alert(objB1.b==objB2.b);
</script>
Why the first alert is true and the second is false? 为什么第一个警报是真的而第二个是假的? Thanks
谢谢
Because the attribute "a" is not a direct property of instances of ClassB (that is, objB1.hasOwnProperty("a") is false) the property is read from its prototype. 因为属性“a”不是ClassB实例的直接属性(即objB1.hasOwnProperty(“a”)为false),所以从其原型中读取属性。 Since there is just one prototype object for all instances of ClassB, objB1.a and objB2.a are literally referring to the same function, defined in their common prototype object.
由于ClassB的所有实例只有一个原型对象,因此objB1.a和objB2.a实际上是指同一个函数,在它们的公共原型对象中定义。 (You can verify that
objB1.a===objB2.a
). (您可以验证
objB1.a===objB2.a
)。
But the attribute "b" is defined as a new function for each and every instance of ClassB and separate function instances are not equal to each other. 但是属性“b”被定义为ClassB的每个实例的新函数,并且单独的函数实例彼此不相等。
Upvoted @maerics's (good) answer, but want to point out something that might not be obvious. Upvoted @ maerics(好)答案,但想要指出可能不明显的事情。 Inside of a (constructor) function,
this
refers to the new instance being created. 在(构造函数)函数内部,
this
指的是正在创建的新实例。 So, each time new ClassA
or new ClassB
is invoked, a new instance is created and this.a
or this.b
refers to a new function assigned to a property of the newly instantiated object. 所以,每一次
new ClassA
或new ClassB
调用,创建一个新的实例,并this.a
或this.b
是指分配给新创建的对象的性质的新功能。
So, looking at your code, a simple question to ask yourself is: "How many new instances of each type are being created?" 因此,查看代码时,一个简单的问题就是:“每种类型的新实例有多少?”
I see just one occurrence of new ClassA()
, which means just one instance of ClassA
is created, therefore, only one function is assigned to this.a
. 我只看到一次
new ClassA()
,这意味着只创建了一个 ClassA
实例,因此,只有一个函数被赋给this.a
But, I see two occurrences of new ClassB()
, therefore, two new functions are created, one for each instance. 但是,我看到两次出现
new ClassB()
,因此,创建了两个新函数,每个函数对应一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.