1.基本的三种方式
<script> //1.方法一 var per1={ name:"卡卡西", age:"15", eat:function(){ console.log("及哈哈"); } }; //方法二 var per2=new Object(); per2.name="大蛇丸"; per2.age=14; per2.eat=function(){ console.log("吃阿布"); } console.log(per2 instanceof Object); //第三种是构造函数, function Person(name,age,sex){ this.name=name; this.age=age; this.play=function(){ console.log("天天打游戏"); } } var p=new Person("名人",19); p.play(); console.log(p instanceof Person); </script>
2工厂的方式
function Person(name,age) { this.name=name; this.age=age; this.sayHi=function () { console.log("您好"); }; } // 工厂的方式 function createPerson(name,age){ var obj=new Object(); obj.name=name; obj.age=age; obj.sayHi=function(){ console.log("你好aa"); } return obj; } var per2=createPerson("小明",20); per2.sayHi();
原文地址:https://www.cnblogs.com/liushisaonian/p/9410810.html
时间: 2024-10-15 02:53:10