JavaScript如何自定义对象

  • 来源:网络
  • 更新日期:2022-03-14

摘要:自定义方法:1、直接通过“属性名/值”来创建,语法“var 对象名={属性名:属性值};”;2、使用“var 对象名=new 构造函数名(args);”语句;3、使用“Object.create(原型对象,descri

自定义方法:1、直接通过“属性名/值”来创建,语法“var 对象名={属性名:属性值};”;2、使用“var 对象名=new 构造函数名(args);”语句;3、使用“Object.create(原型对象,descriptors)”语句。


本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

在Js中,除了Array、Date、Number等内置对象外,开发者可以通过Js代码创建自己的对象。

对象特性

① 结构类似'字典' :对象的属性类似键/值对;属性的名称为字符串,属性的值为任意类型。

② 原型继承:Js的对象可继承原型的属性。

③ 动态结构:可动态新增、删除对象的属性。

④ 引用类型:js中的对象为引用类型。a为一个对象,b=a,修改b也会造成a的修改。

创建对象方式

Js中创建自定义对象,主要通过三种方式:对象直接量、new 构造函数以及Object.create()方法。每一种创建方式继承的原型对象都不同:

① 对象直接量:原型为Object.prototype。

② new 构造函数:原型为构造函数的prototype属性。

③ Object.create():原型为传入的第一个参数,若第一个参数为null,以Object.prototype为原型。

1、对象直接量

说明:直接通过 属性名/值来创建。

语法:var o = { name:'tom', age:22 };

原型:Object.prototype

适用场景:应用在某一特定的作用域里。

示例:

var o = { name: 'tom'}console.log(o.constructor.prototype); // => Object() :对象直接量的原型为Objectconsole.log(o.constructor.prototype === Object.prototype); // true

2、new 构造函数

说明:构造函数也是种函数,但为了区分平常所用的函数,构造函数的函数名采用大骆驼峰写法(首字母大写)。

语法:var o = new ClassName();

原型:构造函数的prototype属性。

示例:

// 1.创建构造函数function People(name) { this.name;}var p = new People('Tom');console.log(p.constructor.prototype); // => People{} :原型为构造函数的prototypeconsole.log(p.constructor.prototype === People.prototype); // => true// 2.自定义对象的多层继承 :constructor返回最先调用的构造函数 function Student(age) { this.age = age;}Student.prototype = new People(); // 设置Student的原型为People对象var s = new Student(22); // 对象初始化时,先调用People(),再调用Student()console.log(s.constructor); // => function People :对象s返回的构造函数为Peopleconsole.log(s.constructor.prototype); // => People{} :原型对象为Peopleconsole.log(s.constructor.prototype === People.prototype); // => true

3、Object.create(prototype, propertyDescriptor) :ECMAScript 5规范

说明:创建并返回一个指定原型和指定属性的对象。

语法:Object.create(prototype, propertyDescriptor)

参数:

①prototype {prototype} :创建对象的原型,可以为null。若为null,对象的原型为undefined。

②propertyDescriptor {propertyDescriptor} 可选:属性描述符。

原型:默然原型型为①参;若①参为null,对象的原型为undefined。

示例:

// 1.建立一个原型为null的对象var o = Object.create(null, { name: { value: 'tom' }});console.log(o.constructor); // => undefined // 2.创建一个原型为Array的对象var array = Object.create(Array.prototype, {});console.log(array.constructor); // => function Array 构造函数 console.log(array.constructor.prototype); // => [] :原型对象为数组// 3.创建一个原型为自定义类的对象function People() { }var p = Object.create(People.prototype, {});console.log(p.constructor); // => function People 构造函数 console.log(p.constructor.prototype); // => People{} :原型对象People

【相关推荐:javascript学习教程】