"this" javascript 中的关键字(例如)

"this" keyword in javascript(as instance)

AFAIK "this" 用于 "property" 和 "parameter" 函数之间的冲突。
请在下面找到我的代码。

<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 contains "this" because person contains firstName as parameter and wants to be as property of person.
My doubt is that this.fullName also has "this" in it even thought there is no parameter with fullName.May be I am wrong(Read that "this" actually creates an instance).
If above is true that it actually creates an instance then my problem is it is creating instance in var p = new person() and why would we create instance of fullName property inside of person

希望对您有所帮助

  1. this.firstname 包含 "this" 因为 person 包含 firstname 作为参数并希望成为 person 的 属性。 - 错误

this用于给对象的属性赋任意值(Person的实例class)

this.firstName = your_var 这会将 your_var 的值分配给 Person 对象的 firstName 属性 如果 your_var 在参数中或您创建的某些本地变量中 您可以为对象

的 属性 分配任何值
  1. 读到 "this" 实际上创建了一个实例 - 错误

this指创建的实例,不创建实例

  1. 你不是在这里创建实例全名,你正在做的是为人对象创建一个实例方法,你可以稍后使用它来获取人的全名

如果您 运行 此代码,您会注意到以下错误:

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() returns firstNamelastName,您 可能 需要传递这些值在创建实例时如果你要调用 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());