面向对象的js
构造函数
<script>
function Student(uname,age.height){
//this指向实例化出来的对象本身
this.name=uname
this.age=age
this.height=height
this.walk=function(){
console.log("walk")
}
}
//new关键字进项实例化
const obj1=new Student("alice",22,170)
console.log(obj1.name)
const obj2=new Student("jone",23,188)
console.log(obj2.name)//完全独立
//问题:walk代码冗余
//作用域被扩大
function walk(){
console.log("walk")
}
Student.prototype//原型对象
</script>
原型对象 通过构造函数的原型对象所分配的函数,是被所有的通过该构造函数创建的对象所共享的
console.log(arr1.__proto__)——指向arr1原型函数
继承
<script>
function Parent(){
this.name="zhangsan"
this.colors=["red","yellow"]
}
Parent.prototype.sing=dunction(){
cinsole.log("father sing~~~~")
}
funxtion Child(){
this.age=21
}
Child.prototype=new Parent()
let c1=new Child()
c1.colors=["pink","green","zhangsan"]
c1.colors.append("zhangsan")
let c2=new Child()
console.log(c1.colors===c2.colors)
//继承的属性会被child实例化的对象共享
//无法对父亲的参数进行传参
</script>
ajax发生请求
<button onlick="load">点击发生请求</button>
<script>
function load(){
//创建XMLHttprequest
let xhe=new XMLHttprequest
//指定请求方式 get 请求的url地址
xhr.open("GET","URL",true)
//设置响应的数据处理
xhr.onreadystatechange=function(){
if(xhr.readyState===4&&xhr.status===200)//4表示请求已经完成且响应结果已经接收
//处理响应的数据
let data=JSON.parse(xhr.responseText)
let newli=document.createElement("li")
newli.innerHTML
}
}
xhr.send()
}
异常处理
<script>
try{
console.log(12/0)
}catch(error){
console.log("除数不难为0")
}
</script>
json