简体   繁体   中英

Object oriented JS

Why it doesn't work? When I'm trying to call example.example() I'm getting TypeError: example.example is not a function.

var example = class {
constructor(){
    this.example = false;
}

id(){
    this.example = !this.example;
    return this.example;
}
};

When I'm trying to call example.example() I'm getting TypeError: example.example is not a function.

example is a reference to an anonymous class, and its constructor can only be invoked with new

You need to call it as

var a = new example();
a.example; //false

Demo

 var example = class { constructor() { this.example = false; } id() { this.example = !this.example; return this.example; } }; var a = new example() console.log(a.example); 

You have created class so you need to make an object of this.It should work by calling like this.

 var example = class { constructor(){ this.example = false; } id(){ this.example = !this.example; return this.example; } }; console.log((new example()).id()); var obj = new example(); console.log(obj.id()); 

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