Using "this." in Javascript Object Variables
In Javascript, unlike C , variables must be explicitly prefixed with "this." to refer to the object they belong to. This is a key difference in object-oriented programming between the two languages.
The "this" keyword in Javascript represents the current context, which is the object on which the function is called. When you declare a variable without "this.", it becomes a local variable within that function scope. To access a property of the object from within a function, you need to use "this." followed by the property name.
Consider the following code:
function foo() { bar = 0; // This creates a local variable this.getBar = function() { return bar; } // This creates a privileged method }
In this code, "bar" is a local variable within the "foo" function, while "getBar" is a privileged method that has access to the local variable. Without using "this.", "getBar" would not be able to access "bar".
This approach of using "this." is necessary for all variables you want to access from within object methods. However, Javascript allows you to define methods on the prototype object instead of instance objects. Methods defined on the prototype are inherited by all instances of that object. In this case, you can avoid using "this." for those methods. Here's an example:
function Foo() { this.bar = 0; } Foo.prototype.getBar = function() { return this.bar; }
In this code, "getBar" is defined on the prototype, so instances of "Foo" inherit this method and can access "bar" without prefixing "this.".
In short, using "this." is essential for accessing object properties from within functions/methods defined inside instance objects. However, it can be avoided by defining methods on the prototype instead.
The above is the detailed content of When and Why Do You Need to Use 'this.' in JavaScript Object Variables?. For more information, please follow other related articles on the PHP Chinese website!