js创建对象的方式

 

基本对象的创建方式

var stu={
		name:'zs',
		age:12,
		eat:function(){
			// 在基本对象内部this指向的是当前的对象stu
			console.log(this);
			console.log(this.name)//zs
			}
		}

工厂方式创建对象

function Student(name,age){
	return{
		name:name,
		age:age,
		eat:function(){
			console.log(this);
		}
	}
}

构造函数方式创建对象

function Student(name,age){
				this.name=name;
				this.age=age;
				this.eat=function(){
					console.log(this.name);
				}
			}

使用的时候先实例化构造函数var stu=new Student('zs',12);

其实用new创建新对象的过程经历了下面三步

/*
                调用new关键字的时候,
                第一步:首先生成一个空对象
                第二步:构造函数中的this指向当前对象
                第三步:执行构造函数代码
 */
   但每次使用构造函数的方法都得实例化一个新对象,而方法又是一样的,造成资源的浪费。

构造函数+构造函数的原型方式创建对象   

function Student(name,age){
				this.name=name;
				this.age=age;
			}
Student.prototype.eat=function(){
        console.log(this.name);
}

    如果构造函数的原型被赋予新的值,则会丢失了constructor

Product.prototype={
				// 可以手动加上constructor
				//constructor:Product,
				buy:function(){
					console.log('buy')
				},
				joinCar:function(){
					console.log('joinCar')
				}
			}

实例对象的__proto__指向构造函数的prototype,可以通过这个方法改写原型上的方法

function Product(title,color){
				this.title=title;
				this.color=color;
			}
			Product.prototype.buy=function(){
				console.log('buy')
			}
var product=new Product('小熊布偶','红色');
product.__proto__.buy=function(){
        console.log('buyed')
}

实例对象.hasOwnProperty('属性')可以判断属性是自有的还是继承来的

function Product(title,color){
				this.title=title;
				this.color=color;
				this.buy=function(){
					alert('确认购买'+this.title)
				}
			}
			Product.prototype.buy=function(){
				console.log('buy')
			}
			Product.prototype.joinCar=function(){
				console.log('加入购物车')
			}
			var p=new Product('口红','401');
			console.log(p.hasOwnProperty("joinCar"))//false
			console.log(p.hasOwnProperty("buy"))//true

使用 a instanceof b构造函数 判断a是否是通过b构造函数构造出来的

	function Product(title,color){
				this.title=title;
				this.color=color;
				this.buy=function(){
					alert('确认购买'+this.title)
				}
			}
			Product.prototype.buy=function(){
				console.log('buy')
			}
			Product.prototype.joinCar=function(){
				console.log('加入购物车')
			}
			var p=new Product('口红','401');
			console.log(p instanceof Product);//true
			console.log(p instanceof Object);//true
			console.log(p instanceof Array);//false

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值