简单回顾一下JavaScript中定义对象的几种方式

最近项目都在使用vue 等框架,感觉有时候把一些基础知识都记得不清楚了。这里简单回顾一下JavaScript中定义对象的几种方式,顺便记录一下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>js对象定义方式</title>
  <style>
	html, body{
		height:100%;
		width:100%;
	}
	body{
		display:table;
	}
	h1{
		display:table-cell;
		text-align:center;
		vertical-align:middle;
	}
  </style>
</head>
<body>
	<h1>请看控制台输出</h1>
</body>

  <script>

    // 字面量
    let Test = {
      name:"字面量"
    }
    console.log(Test)
    
    // 工厂模式
    function CreateTest(name){
      let o = new Object();
      o.name = name;
      return o;
    }
    console.log(CreateTest("工厂模式"))
    
    // 构造模式
    function TestConstructor(name){
      this.name = name;
    }
    console.log(new TestConstructor("构造模式"))
    
    // 原型模式
    function TestPrototype(){}
    TestPrototype.prototype={
      constructor:TestPrototype,
      name:"原型模式",
      say:function(){
        console.log("test");
      }
    }
    console.log(new TestPrototype().name)
    
    // 构造函数原型组合模式
    function TestCombine(name){
      this.name = name;
    }
    TestCombine.prototype={
      constructor:TestCombine,
      say:function(){
        console.log("方法放在原型里进行共享,节省内存")
      }
    }
    console.log(new TestCombine("构造函数原型组合模式"))
  </script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值