How do you create a method for a custom object in JavaScript?

前端 未结 7 1231
野的像风
野的像风 2020-11-28 22:21

Is it like...

var obj = new Object();

obj.function1 = function(){
    //code
}

or something like that?

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 23:12

    var newObj = {
        met1 : function () {
            alert('hello');
        }
    };
    

    Then, the method can be called like such :

    newObj.met1();
    

    Btw, when declaring a new object, use the object literal ({}), not the new Object() constructor.

提交回复
热议问题