Home  >  Article  >  Web Front-end  >  JavaScript Basics--Objects and Properties

JavaScript Basics--Objects and Properties

巴扎黑
巴扎黑Original
2017-07-18 16:44:231065browse

————————————————————————————————————

Object: JavaScript is a prototype-based language and does not have Class, so it will Functions as classes

The data contained in the object can be accessed in two ways

Both properties of the object (property) And method (method)

Attributes are variables belonging to a specific object, and methods are functions that can only be dispatched by a specific object.

An object is a data entity that is composed of some related properties and methods. In JavaScript, properties and methods are accessed using "dot" syntax.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Object-oriented terminology

  • #Object: an unordered collection of attributes, each attribute stores a primitive value, object and function

  • Class: Every object is defined by a class. A class not only defines the object's interface (the properties and methods that developers access), but also defines the object's inner workings (the code that makes the properties and methods work)

  • #Instance: When a program uses a class to create an object, the generated object is called an instance of the class. Each instance behaves the same, but the instance handles an independent set of data.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Four basic abilities

  • Encapsulation: the ability to store relevant information (regardless of data or methods) in objects

  • Aggregation: The ability to store one object within another object

  • Inherited: from another class ( or multiple classes) to derive the properties and methods of a class

  • Polymorphism: the ability to write functions or methods that can be run in multiple ways

—————————————————————————————— ——————————

Built-in objects

  • Data Encapsulated object
    • Methods that support regular objects
    • search

    • match

    • replace

    • split

    • Properties: Object.prototype.constructor:Returns a pointer to the prototype of the object that was created Function reference

    • method:
    • Object.prototype.isPrototypeOf():Detect whether an object exists on the prototype chain of another object

    • Object.prototype.propertyIsEnumerable():Detect whether the specified property name is an enumerable self-property of the current object

    • Object.prototype.toString():Returns a string representing the object

    • Object.prototype.valueOf( ):The returned poemthis value is the object itself

    • ObjectObject is the parent object of all objects in Js, and all objects we create inherit from this

    • method:
    • Object.create():指定原型对象和属性创建一个对象

    • Object.defineProperty():给对象添加/修改一个属性并指定该属性的配置

    • Object.defineProperties():在一个对象上添加或修改一个或者多个自有属性,并返回该对象

    • Object.keys():方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是for-in还会遍历除一个对象从其原型链上继承到得可枚举的属性)

    • Object.getOwnPropertyNames():返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性)组成的数组

    • Object.getOwnPropertyDescriptor():返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性))

    • Object.getPrototypeOf():返回指定对象的原型(也就是该对象内部属性[[Prototype]]的值)

    • Object.freeze():冻结一个对象。冻结对象是指那些不能添加新的属性,不能修改已有属性的值,不能删除已有属性,以及不能修改已有属性的可枚举性、可配置性、可写性的对象。也就是说这个对象永远不能改变的

    • Object.isFrozen():判断对象是否已经被冻结

    • Object.preventExtensions():阻止对象扩展

    • Object.isExtensible():检测一个对象是否可扩展(是否可以在它上面添加新的属性)

    • Object.seal():可以让一个对象密封,并返回被密封之后的对象。密封对象是指那些不能添加新的属性、不能删除已有属性,以及不能修改已有属性的可枚举性、可配置性、可写性,但可能可以修改已有属性的值的对象

    • Object.isSealed():检测一个对象是否被密封sealed

    • Object对象
    • Object.prototype
    • Number对象

    • Boolean对象

    • Array对象

    • Function对象

    • String对象
 1 var myArr = new Array; 2 var str = 'this is a test hello ishello maizi'; 3 var patt = /is/ig; 4 var i = 0; 5 while ((myArr[i] = patt.exec(str)) !== null) 6 { 7     console.log(i + 1 + ':' + myArr[i] + " " + patt.lastIndex); 8     i++; 9 }10 11 str = 'this is a testis';12 patt = /is/ig;13 var res = str.match(patt);14 console.log(res);15 16 res = str.search(patt);17 console.log(res);18 19 res = str.replace(patt, '!');20 console.log(res);21 22 // 将年月日替换为月日年23 str = '2017-06-04';24 res = str.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2-$3-$1');25 console.log(res);26 27 // 调用方法,将匹配到的内容替换成为hugh+匹配内容大写28 str = 'this is a testis';29 res = str.replace(/is/g, func);30 31 function func(match)32 {33     return 'hugh' + match.toLocaleUpperCase();34 }35 console.log(res);36 37 // split38 // 将匹配到的字符串前后拆分39 res = str.split(/\s+/);40 console.log(res);
  • 工具类对象
    • Math对象

    • Date对象
       1 // 显示当前时间 2 console.log(Date()); 3 // 显示毫秒数 4 var d = new Date(138555555550); 5 console.log(d); 6 // 显示填入的时间 7 var d = new Date(2011, 1, 3); 8 console.log(d); 9 // 传入月日10 var d = new Date(10,25);11 console.log(d);12 // Date提供的方法13 console.log(Date.now()); // 自1970年至今所经过的毫秒数14 console.log(Date.parse("2017-01-01")); // 解析一个字符串,返回所经过的毫秒数15 // ...
    • RegExp对象
       1 // 通过test()方法检索字符串中的内容,返回true或false 2 var patt1 = new RegExp("r"); 3 var res1 = patt1.test('this is javascript course'); 4 console.log(res1); 5 // 另一种形式 6 // 加上i表示忽略大小写 7 patt2 = /Javascript/i; 8 res2 = patt2.test('this is javascript course'); 9 console.log(res2);10 // 是否包含[]中的字符11 res3 = /[abc]/.test('Brlue');12 // 加上^表示除了abc之外的13 res4 = /[^abc]/.test('Brlue');14 // 检测是否包含数字15 res5= /[0-9]/.test('999');16 // 检测是否包含字母17 res5= /[a-z]/.test('999');18 // 是否出现了以下几个19 res5= /php|javascript|ios/.test('php');20 console.log(res3);21 console.log(res4);22 console.log(res5);
  • 错误对象
    • 通常使用try/catch/finally来捕获Error错误

    • Error类型
    • EvalError

    • InternalError

    • RangeError

    • ReferenceError

    • SyntaxError

    • TypeError

    • URIError

    • Error对象
       1 try 2 { 3     // 当调用不存在的notExists(),e.name和e.message存放的错误名称和错误信息 4     // notExists(); 5     var n = 0; 6     if (n == 0) 7     { 8         // 手动抛出一个错误信息 9         throw new Error('Throw an error message');10     }11 }12 catch (e)13 {14     console.log(e.name);15     console.log(e.message);16 }17 finally18 {19     // finally中的总是被调用20     console.log('i am in finally');21 }22 23 try24 {25     notExists();26 }27 catch (e)28 {29     // 判断错误的实例化类型30     if (e instanceof EvalError)31         console.log('this is a EvalError');32     else if (e instanceof SyntaxError)33         console.log('this is a SyntaxError');34     else if (e instanceof ReferenceError)35         console.log('this is a ReferenceError');36     else37         console.log('An unknown errorr');38 }39 // 对Error对象重写40 function myError(msg)41 {42     this.name = "myError'sname";43     this.message = msg || "myError'info";44 }45 // 通过Object.create()创建错误原型46 myError.prototype = Object.create(Error.prototype);47 myError.prototype.constructor = myError;48 try49 {50     throw new myError();51 }52 catch (e)53 {54     console.log(e.name);55     console.log(e.message);56 }

自定义对象

  • 通过var obj = {} 对象字面量法

  • 通过var obj = new Object()创建

  • 通过函数构造创建对象

    p.s. 使用的时候通过new操作符得到对象

    用构造器创建对象的时候可以接收参数

    构造器函数的首字母最好大写,区别其他的一般函数

    • 当我们创建对象的时候,实际上同时也赋予了该对象一种特殊的属性,即构造器属性

    • 这个构造器属性实际上是一个指向用于创建该对象的构造器函数的引用

    • function Person(){}

    • var Persion = function(){}

    • 构造器属性(constructor property)
    • 通过instanceof操作符可以检测一个对象是否由某个指定的函数构造器创建

  • 通过Object.create()创建对象

 1 /*********************************** 2  * 对象字面量 3  ***********************************/ 4 var oTest = {}; 5 document.write(typeof oTest + "
"); 6 var oTest2 = { x: 1, 'y': 2, "z": 3 }; 7 document.write(oTest2.x + " " + oTest2.y + " " + oTest2.z + "
"); 8 var oTest3 = { 9     username: 'rog91222',10     passwd: '123123',11     person: {12 firstname: "hugh",13 lastname: "dong"14     },15     age: 2016 }17 document.write(oTest3.username + " " + oTest3.person.firstname + " " + oTest3.age + "
");18 /***********************************19  * new Object()创建对象20  ***********************************/21 var oTest4 = new Object();22 /***********************************23  * 通过构造器函数的形式创建对象24  ***********************************/25 function funcTest(num1, num2) {26     this.n1 = num1;27     this.n2 = num2;28 }29 var oTest5 = new funcTest(1, 2);30 document.write(oTest5.n1 + " " + oTest5.n2 + "
");31 // 通过instanceof检测是否由函数构造器构造的32 document.write(oTest5 instanceof funcTest);33 document.write("
")34 /***********************************35  * 通过Object.create()创建对象36  ***********************************/37 var oTest6 = Object.create({ x: 1 });38 // 不继承任何方法39 var oTest7 = Object.create(null);40 // 创建一个普通的空对象41 var oTest8 = Object.create(Object.prototype);

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

对象特性

  • 原型(prototype)
    • 通过对象字面量的形式创建,则使用object.prototype作为它们的原型。

    • 通过new和构造函数创建,则使用构造函数的prototype作为它们的原型。

    • 如果通过Object.create()创建,使用第一个参数(null)作为它们的原型

      var obj = Object.create({ x: 1 });

  • (class)

  • 扩展标记(extensible flag)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

对象的结构

  • 声明对象obj,对象有2个属性 x=1,y=2,每个属性都有对应的属性特性,对象也有3个对象特性

  • 对象的原型链:

    如图所示,当在对象中找不到属性z时,会向方法的原型查找,继续向对象的原型查找,直到顶层null位置。

    每个对象都和另外一个对象关联,就构成了一个原型链,每一个对象都从原型继承属性。

    <>

       

       

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

检测对象上是否有某个属性

  • in(包括原型上的)

  • hasOwnProperty(仅检测对象自己有的属性)
 1 function foo()  {} 2 foo.prototype.z = 5; 3 var obj1 = new foo(); 4 obj1.x = 1; 5 obj1.y = 2; 6 console.log('x' in obj1); 7 console.log('y' in obj1); 8 console.log('toString' in obj1); 9 console.log('nonono' in obj1);10 console.log(obj1.hasOwnProperty('x'));11 console.log(obj1.hasOwnProperty('z'));

————————————————————————————————————————————

属性

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

数据属性:每个属性有4个描述行为的特性:

  • [writable]:是否能修改属性的值

  • [enumerable]:是否通过for in 循环返回属性(是否可以被枚举)

  • [configurable]:是否能通过delete删除,能否修改属性的特性,能否修改访问器属性

  • [value]:包含这个属性的数据值,读取属性值的时候从这个位置读取。默认值为undefined

存取器属性

  • get:获取属性的值

  • set:设置属性的值

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

属性操作

p.s. 正常属性名可以放在""''或不放引号内,但如果包含特殊字符、保留字、数字开头,必须放在引号之间

  • 访问属性

  • 添加属性

  • 修改属性

  • 删除属性

  • 遍历属性

 1 var person = 2 { 3     fName : 'hugh', 4     lName : 'dong', 5     age : 20 6 }; 7 // 通过.或[]来实现查询属性 8 console.log(person.fName); 9 console.log(person['lName']);10 console.log(person["age"]);11 // 如果属性不确定,需要使用[]来读取属性,此处key不能加引号12 var key = 'fName';13 console.log(person[key]);14 // 在对象内部通过this获取属性15 function PersonInfo(fName, lName, age)16 {17     this.firstName = fName;18     this.lastName = lName;19     this.year = age;20 }21 var person1 = new PersonInfo('wang', 'er', 30);22 console.log(person1.firstName);23 console.log(person1.lastName);24 console.log(person1.year);25 // 添加属性26 var obj = {};27 obj.userName = 'username';28 obj.passwd = '123456';29 obj['permissions'] = 'admin';30 console.log(obj.userName);31 console.log(obj.passwd);32 console.log(obj.permissions);33 // 修改属性34 obj.passwd = '123.com';35 console.log(obj.passwd);36 // 删除属性,删除后再打印该属性为undefined37 // p.s.delete只能删除自身的属性,不能删除集成的属性38 // 要删除继承属性,只能从定义它的属性的原型对象上删除它,会影响到所以继承这个原型的对象39 // delete只是断开属性和宿主对象的联系,而不会去操作属性的属性40 delete obj.permissions;41 console.log(obj.permissions);42 // 遍历属性43 // i存放的是属性名称,obj[i]存放的是属性值44 for (var i in obj)45 {46     console.log(i + ":" + obj[i]);47 }48 // 对象中有方法49 var obj1 =50 {51     user : '111',52     pass : '222',53     sayHi : function (x)54     {55         return this.user + x + 1;56     }57 }58 console.log(obj1.sayHi(3));

The above is the detailed content of JavaScript Basics--Objects and Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn