AFAIK"this"用于"property"与;函数的"参数"
请在下面找到我的代码。
<script>
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstname + " " + this.lastname
}
}
var p = new person();
document.write("fullname is " + p.fullName());
</script>
如果我在以下方面有错,请在这里纠正我
this.firstName包含"this",因为person包含firstName作为参数,并希望作为person的属性
我的疑问是this.fullName中也有"this",甚至认为fullName没有参数。可能我错了(请阅读"this"实际上创建了一个实例)
如果上面是真的,那么它实际上创建了一个实例那么我的问题是它正在varp = new person()
中创建实例,为什么我们要在人员中创建fullName
属性的实例
希望这能帮助
- this.firstname包含"this",因为person包含firstname作为参数,并希望作为person的属性。-错误
this
用于将任何值分配给对象(Person类的实例)的属性
this.firstName = your_var
这将把your_var
的值分配给Person
的对象的firstName
属性,不管您的_var是在参数中还是在您创建的某个本地var中您可以为对象的属性指定任何值
- 请阅读"this"实际上创建了一个实例-错误
this
引用创建的实例,不创建实例
- 您不是在这里创建实例全名,您所做的是为person对象创建一个实例方法,稍后可以使用该方法来获取人员的全名
如果运行此代码,您会注意到以下错误:
Uncaught TypeError: p.fullname is not a function on line 10
方法调用的大小写错误。更正后的代码如下:
document.write("fullname is " + p.fullName());
您的属性类似于fooBar
,并且您将它们作为foobar
返回,这些位置:
this.firstName = firstName; // firstName
this.lastName = lastName; // lastName
//but below as firstname, lastname instead of firstName and lastName
return this.firstname + " " + this.lastname
也在这里:
this.fullName = function(){ ... }
但您将函数称为p.fullname()
此外,我认为,由于fullName()
返回firstName
和lastName
,如果您要调用fullName()
,则在创建实例时可能需要传递这些值,因为此函数需要它们,否则您将得到undefined
,如下所示:
var p = new person('Foo', 'Bar');
现在它正在工作:JS Fiddle
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
return this.firstName + " " + this.lastName
}
}
var p = new person('Foo', 'Bar');
// check the console
console.log("fullname is " + p.fullName());