how to initialize a class object in javascript

跟風遠走 提交于 2019-12-13 06:59:13

问题


I have a java script class say "myjavascript.js". I have the following class

var myClass= function () {
        this.property2 = '';
        this.property3 = '';
        this.property4 = '';
        this.property5 = '';

        this.say() = function () {
            alert('Say Hello');
        }

I have a function which is triggered on some event.

function myFunction(){
var myClassObj= new myClass();
myClassObj.property2 = 'property2' ;
myClassObj.property3 = 'property2' ;
myClassObj.property4 = 'property2' ;
myClassObj.property5 = 'property2 ';
myClassObj.say();
}

On triggering function I am getting the this error

Uncaught TypeError: undefined is not a function

Keep in mind both are in the same file.


回答1:


this.say() is the error. You are calling the function, not defining it.

 this.say = function () {
            alert('Say Hello');
        }


来源:https://stackoverflow.com/questions/26550413/how-to-initialize-a-class-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!