Object类

  • 其他对象的基类
  • Object类的所有属性和方法在其他对象中都存在

    Object中定义的属性

    constructor

  • 用于创建当前实例的函数

    • 构造函数方式创建的对象

      1. function Person(){}
      2. const person = new Person()
      3. console.log(person.constructor === Person)
      4. console.log(person.constructor)

      image.png

    • 类方式创建的对象

      1. const stu = new Student()
      2. console.log(stu.constructor);
      3. console.log(stu.constructor === Student);

      image.png

      Object中定义的方法

      hasOwnProperty(propertyName)

  • 用于判断当前的实例对象上是否存在给定的属性(而不是来自原型链上查找的)

    • 属性是否来自实例自身
  • 属性名propertyName必须是字符串或符号 ```javascript function Person(){} Person.prototype.clazz = “三年二班” class Student extends Person{} const stu = new Student() stu.name = “liuxiangwei”

console.log(stu.clazz); // “三年二班” console.log(stu.name); // “liuxiangwei” console.log(stu.hasOwnProperty(‘name’)); // true console.log(stu.hasOwnProperty(‘clazz’));// false

  1. ```javascript
  2. for (const key in stu) {
  3. console.log(key); // name和clazz
  4. }
  5. for (const key in stu) {
  6. if(stu.hasOwnProperty(key)){
  7. console.log(key); // 只有name
  8. }
  9. }

isPrototypeOf(object)

  • 用于判断当前对象是否是另一个对象的原型 ```javascript function Person(){} class Student extends Person{} console.log(Person.isPrototypeOf(Student)); //true

let person = new Person() console.log(Person.prototype.isPrototypeOf(person)) //true

<a name="XUvxR"></a>
#### propertyIsEnumerable(propertyName)

- 用于判断给定的属性是否可以使用for-in语句枚举
```javascript
console.log(stu.propertyIsEnumerable('name'));  //true
console.log(stu.propertyIsEnumerable('clazz')); //false

toLocaleString()

  • 返回对象的字符串表示

    toString()

  • 返回对象的字符串表示

    valueOf()

  • 返回对象对应的字符串、数值或布尔值表示

  • 通常与toString()返回的值相同

    class Student extends Person{
      toString(){
      return "abc"
      }
      valueOf(){
      return false
      }
    }
    console.dir(stu.toString()); // "abc"
    console.dir(stu.toLocaleString()); // "abc"
    console.dir(stu.valueOf()); // false
    

    Object类的静态方法

    Object.is()

    Object.assgin()

    Object.defineProperty()

  • 参数

    • 参数一 要给其添加属性的对象
    • 参数二 属性的名称
    • 参数三 描述符对象

      Object.getPrototypeOf()

  • 返回参数的proto对应的值

    console.log(Object.getPrototypeOf(person) === Person.prototype) //true