Reputation: 2848
function foo(){
this.a = 123;
b();
function b(){
alert(this.a);//undefined
}
}
var o = new foo();
o.a = 456;
i'm new in js oop, i try to access a public property from private method 'b(){}'
but it shows undefined
and i also wish to change this property from outside, but consider the object will construct first before I change property value, anyone how to fix this?
Upvotes: 1
Views: 91
Reputation: 12439
prototype
is used to create a class and its methods in javascript
. I modified your example according to native javacript
:
function foo(){
this.a = 123;
this.b();
}
foo.prototype.b = function b(){
alert(this.a);
}
var o = new foo();
o.a = 456;
Upvotes: 1
Reputation: 1162
I rewrote it for you in ECMA6 syntax so it's easier to read, and corrected it:
class foo {
constructor() {
this.a = 123;
this.b();
}
b() {
alert(this.a);
}
}
var o = new foo();
o.a = 456;
Upvotes: 2
Reputation: 35481
The way this
gets bound has nothing to do with where you define a function and everything to do with how you call a function.
In your case, you are calling the function as a regular function which means this
will get bound to the global object (or undefined
in strict mode).
Upvotes: 2