● 以前的创建面向对象的方法 :function方式
<script>
function CreateList(name){
this.name = name
}
CreateList.prototype.getName = function(){
console.log('111',this.name)
}
var obj1 = new CreateList("yiyi")
obj1.getName()
</script>
- 现在为了和其他语言保持格式的一致,引入了用class类创建面向对象:
<script>
class CreateList{
//构造器函数
constructor(name){
this.name = name
}
//原型里的方法
getName(){
console.log('111',this.name)
}
}
var obj = new CreateList("yiyi")
obj.getName()
</script>
- 把属性放在构造器函数constructor里面, 然后把原型函数放在这个constructor后面,直接先方法;
- CreateList是封装的一个类,类里面有构造函数,还有原型中挂着的一个方法;
- 现在最常用的还是class封装类的这个方式