简体   繁体   中英

javascript oop private method access public property

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?

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).

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM