发布网友 发布时间:2022-04-30 18:59
共1个回答
热心网友 时间:2022-04-22 16:54
在JavaScript中定义对象可以采用以下几种方式:1.基于已有对象扩充其属性和方法2.工厂方式3.构造函数方式4.原型(“prototype”)方式5.动态原型方式 -- 1.基于已有对象扩充其属性和方法object.name = "zhangsan";object.sayName = function(name){ this.name = name; alert(this.name);}object.sayName("lisi"); -- 2.工厂方式 function createObject() { var object = new Object(); object.username = "zhangsan"; object.password = "123"; object.get = function() { alert(this.username + ", " + this.password); } return object;}var object1 = createObject();var object2 = createObject();object1.get(); -- 采用带参数的构造方法:function createObject(username, password){ var object = new Object(); object.username = username; object.password = password; object.get = function() { alert(this.username + ", " + this.password); } return object;}var object1 = createObject("zhangsan", "123");object1.get();