最近项目都在使用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>