[英]trying to understand javascript objects
I've written this piece of code to try help me understand how objects work in js a bit more. 我编写了这段代码来尝试帮助我更多地了解对象在js中的工作方式。
function person(personName){
var thiz = this;
var nameOfMe = (typeof(personName) === 'undefined')? 'default':personName;
var faveFood = 'stuff';
thiz.speakName =function(){
alert('I am '+ thiz.nameOfMe);
}
thiz.gotFoodAlert = function(){
alert('Yummy! I haz ' + thiz.faveFood )
}
}
var someGuy = new person('joe');
someGuy.faveFood = 'cheesecake';
someGuy.speakName();
var elseGuy = new person();
elseGuy.nameOfMe = 'bob';
elseGuy.speakName();
I'm trying to simulate a classical inheritance model to build a class then instantiate a person. 我正在尝试模拟经典继承模型来构建类,然后实例化一个人。 Setting it separately in elseGuy.speakName() alerts 'bob' ok. 在elseGuy.speakName()中单独设置它会提醒'bob'正常。
What I don't understand is why doesnt the someGuy.speakName() alert 'joe' when I instantiate? 我不明白的是,为什么我实例化时someGuy.speakName()不会警告“ joe”?
update: on further reflection and taking notes from people commented, I should just give up trying to simulate a classical inheritance model. 更新:在进一步思考并记下人们的评论时,我应该放弃尝试模拟经典继承模型的尝试。
Because nameOfMe
is not a property of this
in the first example. 因为nameOfMe
不是一个属性this
在第一个例子。 Try the following instead: 请尝试以下操作:
function person(personName) {
var nameOfMe = (typeof personName === 'undefined')? 'default':personName;
var faveFood = 'stuff';
this.speakName = function () {
alert('I am ' + nameOfMe);
}
this.gotFoodAlert = function () {
alert('Yummy! I haz ' + faveFood )
}
}
Even better: 更好的是:
function Person(personName) {
this.nameOfMe = personName ? 'default' : personName;
this.faveFood = 'stuff';
}
Person.prototype.speakName = function () {
alert(this.nameOfMe);
};
Person.prototype.gotFoodAlert = function () {
alert('Yummy! I haz ' + this.faveFood);
};
You have to set nameOfMe
as a property of thiz
: 您必须将nameOfMe
设置为thiz
的属性:
thiz.nameOfMe = (typeof(personName) === 'undefined')? 'default':personName;
Also, unless you absolutely have to, why don't you use the normal this
instead of thiz
? 另外,除非绝对必要,否则为什么不使用常规this
代替thiz
?
thiz = this
aliasing is unnecessary here. thiz = this
此处不需要混叠。 You only need it for "private" properties by additional closures. 您仅需要通过其他闭包将其用于“私有”属性。 thiz.nameOfMe
is causing an additional closure here, needlessly. thiz.nameOfMe
不必要地导致此处的其他关闭。 thiz.nameOfMe
is not "joe"
because the object referred to by thiz
does not have a nameOfMe
property yet. thiz.nameOfMe
的值不是"joe"
因为thiz
引用的对象还没有nameOfMe
属性。 The nameOfMe
variable in constructor code is something else. 构造函数代码中的nameOfMe
变量是其他内容。 person
instance, that is, an object that has person
as its constructor, and the object that person.prototype
currently refers to next in its prototype chain. 您正在创建一个person
实例,即一个以person
为构造函数的对象,并且person.prototype
当前引用其原型链中的下一个对象。 Nothing more, nothing less. 仅此而已。 Person
. 构造函数标识符以大写字母Person
开头是一种很好的代码样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.