es5中没有类的概念,但是可以通过构造函数创建对象
function Point(x, y) {
this.x = x;
this.y = y;
}
//es5中给point方法重写或添加一个tostring方法 使用prototype(原型)
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
//创建对象p
var p = new Point(1, 2);
//通过p调用tostring方法
console.log(p.toString());
es6中引入了类的概念
创建类的关键词 class
创建构造方法的关键词constructor
在es6中可以直接添加方法(方法之间不要加逗号),一个类只能定义一个构造方法,即使参数个数 与构造方法不同,也会调用当前的构造方法,
<script>
class Pointa{
// constructor() {
// console.log('无参构造方法,如果没有定义构造,自动添加空参构造方法')
// }
constructor(x,y){
this.x=x;
this.y=y;
}
toString(){
return '('+this.x+','+this.y+')';
}
}
var pa=new Pointa(3,4);
console.log(pa.toString());//(3,4)
</script>
可以使用使用构造方法 创建另外的对象
<script>
class Foo {
constructor() {
return Object.create(null);
}
}
//与java相同 instanceof 可以判断当前对象是否属于当前类
console.log(new Foo() instanceof Foo)// false
console.log(new Foo())//object
</script>
hasOwnProperty() 返回一个布尔值,判断对象本身是否包含对应属性
<script>
var o1=new Object();
o1.country='china';
function deleteproperties(){
delete o1.country; //删除o1的country属性
}
console.log(o1.hasOwnProperty('调用deleteproperties前:'+'country'));//调用deleteproperties前:true
deleteproperties();
console.log(o1.hasOwnProperty('调用deleteproperties后:'+'country'));//调用deleteproperties后:false
</script>
<script>
class Pointa{
// constructor() {
// console.log('无参构造方法,如果没有定义构造,自动添加空参构造方法')
// }
constructor(x,y){
this.x=x;
this.y=y;
}
toString(){
return '('+this.x+','+this.y+')';
}
}
var p=new Pointa(1,2);
console.log(p.hasOwnProperty('x'));//true
console.log(p.hasOwnProperty('y'));//true
console.log(p.hasOwnProperty('toString'));//false
console.log(p.__proto__.hasOwnProperty('toString'));//true
</script>
方法是挂在原型区的,所以上面:p.hasOwnProperty('toString')为false,p.__proto__.hasOwnProperty('toString')为true