0 对象

0.1简介

JavaScript 中的所有事物都是对象:字符串、数值、数组、函数…此外,JavaScript 允许自定义对象。
JavaScript 提供多个内建对象,比如 String、Date、Array 等等。 对象只是带有属性和方法的特殊数据类型。

对象只是一种特殊的数据。对象拥有属性和方法。

0.2创建对象

创建新对象有两种不同的方法:

  1. 定义并创建对象的实例
1
2
3
4
5
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
  1. 使用函数来定义对象,然后创建新的对象实例
1
2
3
4
5
6
7
8
9
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");

也可以把方法添加到 JavaScript 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myMother.changeName("Doe");

1 Object对象

Object是javaScript中一切对象的父类对象

0.1 创建Object对象

语法

obj = new Object([value])

参数
obj 必需 Object 对象分配到的变量名称。
可选 任一 JavaScript 基元数据类型(数字、布尔值或字符串)。 如果值是一个对象,则返回的对象是未修改的。 如果值是 null、“未定义”或“未提供”,则创建无内容的对象。

0.2 属性

属性 描述
__proto__ 属性 指定对象的原型。
constructor 属性 指定用于创建对象的函数。
prototype 属性 为对象的类返回原型的引用。
  1. proto 属性
    语法:

    object.__proto__

object 必需。要对其设置原型的对象。__proto__ 属性名称以两个下划线开始和结束。

1) 下面的代码示例显示如何为对象设置原型。

1
2
3
4
5
6
7
8
9
10
function Rectangle() {
}

var rec = new Rectangle();

if (console && console.log) {
console.log(rec.__proto__ === Rectangle.prototype); // Returns true
rec.__proto__ = Object.prototype;
console.log(rec.__proto__ === Rectangle.prototype); // Returns false
}

2) 下面的代码示例演示如何通过将属性添加到原型来将其添加到对象中。

1
2
3
4
5
6
7
8
9
10
11
12
13
var proto = { y: 2 };

var obj = { x: 10 };
obj.__proto__ = proto;

proto.y = 20;
proto.z = 40;

if (console && console.log) {
console.log(obj.x === 10); // Returns true
console.log(obj.y === 20); // Returns true
console.log(obj.z === 40); // Returns true
}

3) 下面的代码示例通过在 String 对象上设置新原型将特性添加到该对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var stringProp = { desc: "description" };

String.__proto__ = stringProp;
var s1 = "333";
var s2 = new String("333");

if (console && console.log) {

console.log(String.desc === "description"); // Returns true
console.log(s1.desc === "description"); // Returns false
console.log(s2.desc === "description"); // Returns false

s1.__proto__ = String; // Can't be set.
s2.__proto__ = String;

console.log(s1.desc === "description"); // Returns false
console.log(s2.desc === "description"); // Returns true
}

最后更新: 2018年12月02日 19:16

原始链接: http://linjiad.github.io/2018/11/27/JavaScript对象/

× 请我吃糖~
打赏二维码