JavaScript学习笔记 创建对象

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值