<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>类</title>
<script type="text/javascript">
//JavaScript中的类本质上还是函数,语法是一种语法糖
class Point{
static pi=3.14; //类似于java的成员变量 //static属性目前还没有加入到标准里面
m; //实例的属性
n;
constructor(x,y){
//x,y是实例的属性
this.x=x;
this.y=y;
//不推荐
this.print=function(){
alert(this.x);
}
}
//定义了方法 属于父亲
toString(){
window.alert("我的x轴坐标是"+this.x+"我的y轴坐标是"+this.y);
}
//方法 使用Es6的模板语法,改写拼接字符串
toValue(){
window.alert(`我的x轴是${this.x},我的y轴是${this.y}`);
}
//静态方法
static println(){
alert("我是静态方法");
}
}
var p=new Point(10,10);//p实例中存在x,y
var p2=new Point(20,20);//p2实例中也存在x,y
p.toValue();
p.toString();
console.log(p);//默认调用了toString() 调试代码
console.log(p.hasOwnProperty("toString"));//false
console.log(p.hasOwnProperty("print"));//true
Point.println();//静态方法通过类名调用
//p.println();//报错,静态方法不属于实例
console.log(typeof Point);//function 理论上js中的类依然是一个构造函数
console.log("----------------------------------");
//上述的原理
function Pointl(x,y){
this.x=x;
this.y=y;
}
//函数是一个函数式对象 有prototype属性,指向原型
Pointl.prototype.toString=function(){
window.alert("我的x轴坐标是"+this.x+"我的y轴坐标是"+this.y);
}
Pointl.prototype.toValue=function(){
window.alert(`我的x轴是${this.x},我的y轴是${this.y}`);
}
</script>
</head>
<body>
</body>
</html>
JavaScript之类和对象
最新推荐文章于 2022-07-30 23:08:11 发布