[英]Why include .prototype in the function?
I am reading John Resig's slideshow http://ejohn.org/apps/learn/#78 Its not clear to me why i need to include .prototype
in the line Me.prototype = new Person();
我正在阅读John Resig的幻灯片http://ejohn.org/apps/learn/#78对我来说不清楚,为什么我需要在行Me.prototype = new Person();
加入.prototype
Me.prototype = new Person();
function Person(){}
Person.prototype.getName = function(){
return this.name;
};
function Me(){
this.name = "John Resig";
}
Me.prototype = new Person();
var me = new Me();
assert( me.getName(), "A name was set." );
Think of it this way, if every person is going to have a name, it's easier to assign the getName
function to it's prototype. 这样考虑一下,如果每个人都有一个名字,则将getName
函数分配给它的原型会更容易。
In this case, you have a Person that has a prototype function to get a name, and a few lines below you have a Me function that assigns a name by default. 在这种情况下,您有一个具有原型函数来获取名称的Person ,下面的几行有一个Me函数,默认情况下会分配一个名称。 Since we want to incorporate the getName
function, we use the Person
which already has that function object built-in. 由于我们要合并getName
函数,因此我们使用已经内置了该函数对象的Person
。 When you construct Me()
and assign to me
you can call getName()
and use that to return the name, which by default is "John Resig" 当构造Me()
并分配给me
您可以调用getName()
并使用它返回名称,默认情况下为“ John Resig”
The same thing can be achieved without prototype, like this 不需要原型就可以实现同样的事情
function Me(){
this.name = "John Resig";
this.getName = function () {
return this.name;
}
}
var me = new Me();
...BUT by using prototype, it helps create objects a lot faster, you can refer to this answer as well. ...但是通过使用原型,它有助于更快地创建对象,您也可以参考此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.