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

前端 未结 7 1239
野的像风
野的像风 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:06

    Generally use the prototype property:

    function YourObject()
    {
        //
    }
    
    YourObject.prototype.yourMethod= function()
    {
       //
    }
    

    One thing I haven't seen anyone mention yet is why you might want to use the prototype property over, say, object-literal notation: doing so ensures the function definition gets shared across all instances of the objects created from your function prototype, rather than once per instantiation.

提交回复
热议问题