【JS】原生JS以对象作为构造器创建实例Object.create()

本文介绍如何在JavaScript中使用不同方法实现对象继承,包括利用ES6的Object.create方法、构造函数以及工厂方法来创建对象实例,并展示了如何通过继承拓展对象功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用对象字面量作为其他对象的基础
创建Person对象 具有下列属性

var Person = {
 	firstName : 'quanquan',
 	lastName : 'xu',
 	birthDate : new Date('1992-01-04'),
 	gender : 'female',
 	getAge : function(){
 		var today = new Date();
 		var diff = today.getTime() - this.birthDate.getTime();
 		console.log( diff )
 		var year = 1000*60*60*24*365.25;
 		return Math.floor(diff/year);
 	},
 	toString : function(){
 		return this.firstName + ' ' + this.lastName + ' is a ' + this.getAge() + ' year-old ' + this.gender;
 	}
 }

创建Person的类型的实例
ES6 Object.create 提供对象间联系的方法
修改原型中的一些属性 未修改的则继承Person

var yuan = Object.create( Person );

 console.log( yuan.__proto__ );//查看yuan的原型Person
 console.log( yuan.__proto__ === Person);//true

 yuan.firstName = 'yuanyuan';//修改firstName
 yuan.lastName = 'hu';//修改lastName
 yuan.birthDate = new Date('1990-10-25');//修改birthDate

 console.log( yuan.toString() );//yuanyuan hu is a 27 year-old female

当ES6 不支持Object.create时可以使用一下方法创建实例
构造函数的方式

if( typeof Object.create != 'function' ){
 	Object.create = function( o ){
 		function F(){}
 		F.prototype = o;
 		return new F();
 	}
 }

当你不喜欢使用Object.create时 可以使用工厂方法

var Animal = {
 	type : 'pig',
 	age : '3',
 	gender : 'female',
 	showInfo : function(){
 		return this.type + ' ' + this.age + this.gender;
 	},
 	extend : function(config){
 		var tmp = Object.create( this );
 		for( var key in config ){
 			if( config.hasOwnProperty( key ) ){
 				tmp[ key ] = config[ key ];
 			}
 			
 		}
 		return tmp;
 	}

 }
 //dog继承Animal
 var Dog = Animal.extend({
 	type : 'dog',
 	age : '4',
 	showInfo : function(){
 		return 'this dog' + this.type + this.age;
 	}
 });
 //cat继承Dog 但拥有Animal的属性
 //如果Dog的属性与Animal的属性冲突 那么继承的是Dog的属性
 var cat = Dog.extend({
 	type : 'cat',
 	age : '5'
 });
 console.log(Dog.showInfo());//this dogdog4
 console.log(cat.__proto__);//Dog
 console.log(Dog.__proto__);//Animal
 console.log( cat.showInfo() );//this dogcat5

判断Dog的原型是否是Animal isPrototypeOf

 console.log( Animal.isPrototypeOf( Dog ) );//true
 console.log( Dog.isPrototypeOf( Animal ) );//false

返回当前对象的原型 getPrototypeOf

console.log( Object.getPrototypeOf(cat) );//Animal

参考书籍:《精通javascript》(第二版) 第三章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值