一、引用类型-对象
1、普通声明变量
let student = new Object();
student.id=100
student.name="JSON"
student.sayhi =function(){
console.log("我叫"+this.name+",id是"+this.id)
}
student.sayhi()
console.log(student.name)
2、字面量声明
let student ={
id :200,
name:"tom",
sayhi: function(){
console.log("我叫"+this.name+",id是"+this.id)
}
}
student.sayhi()
console.log(student.name)
3、构造函数 在构造函数中定义类的属性和方法
function student3(id,name){
this.id = id,
this.name = name,
this.sayhi = function(){
console.log("我叫"+this.name+",id是"+this.id)
}
}
let student = new student3(300,"liah")
let student1 = new student3(100,"wnagyw")
let student2 = new student3(320,"lssdh")
student.sayhi()
student1.sayhi()
student2.sayhi()
二、原型应用
Student3.prototype.count =100;
Student3.prototype.study = function(){
console.log("共享学习空间")
}
let student = new Student3(300,"liah")
let student1 = new Student3(100,"wnagyw")
let student2 = new Student3(320,"lssdh")
student.study()
student1.study()
student2.study()
student.sayhi()
student1.sayhi()
student2.sayhi()
console.log(student.sayhi == student1.sayhi)
console.log(student.study == student1.study)
console.log(student)
console.log(student1)
console.log(student2)
典型案例