Object的方法

Object的方法,第1张

Object的方法整理 1.概述

Js的所有其他对象都继承于Object对象,都是Object的示例。
Object对象的原生方法分为两类:

本身的方法实例的方法

(1)Object对象本身的方法
定义在Object对象的方法。

Object.print = function (o) { console.log(o) };

上面代码中,print 方法就是直接定义在 Object 对象上的

(2)Object的实例方法
定义在Object原型对象Object.prototype上的方法,可以被Object实例直接使用。

Object.prototype.showThis = function () {
  console.log(this);
};

const obj = new Object();
obj.showThis() // Object

2.Object()

Object 本身是一个函数,可以当作工具方法使用,将任意值转为对象,常用于保证某个值一定是对象

let obj = Object();
// 等同于
let obj = Object(undefined);
let obj = Object(null);
obj instanceof Object // true

如果参数为空(或者为undefined和null),Object()返回一个空对象。

instanceof 用来验证,一个对象是否为指定的构造函数的实例
obj instanceof Object 返回 true,就表示 obj 对象是 Object 的实例

如果参数是原始类型的值,则会将其转为对应的包装对象的示例

let obj = Object(1);
obj instanceof Object // true
obj instanceof Number // true

let obj = Object('foo');
obj instanceof Object // true
obj instanceof String // true

如果Object方法的参数是一个对象,它总是返回该对象,即不用转换。

let arr = [];
let obj = Object(arr); // 返回原数组
obj === arr // true

let value = {};
let obj = Object(value) // 返回原对象
obj === value // true

let fn = function () {};
let obj = Object(fn); // 返回原函数
obj === fn // true

利用这一点,可以判断变量是否为对象

function isObject(value) {
  return value === Object(value);
}

isObject([]) // true
isObject(true) // false
3.静态方法

静态方法是指 Object 自身的方法

3.1 Object.keys(), Object.getOwnPropertyNames()

Object.keys 返回对象可枚举属性组成的数组,Object.getOwnPropertyNames返回包含对象不可枚举属性组成的数组

const a = ['Hello', 'World'];

Object.keys(a) // ["0", "1"]
Object.getOwnPropertyNames(a) // ["0", "1", "length"]
3.2 其他方法 3.2.1对象属性模型的相关方法 Object.getOwnPropertyDescriptor(o, prop) 获取某个属性的描述对象。 o(any):对象prop(string | number | symbol):属性名
const obj = {
name:'lxj',
age:'23'
}
console.log(Object.getOwnPropertyDescriptor(obj, 'name'));
// { value: 'lxj', writable: true, enumerable: true, configurable: true }
Object.defineProperty(obj, prop, descriptor) 通过描述对象,定义某个属性

直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象。

obj(any) 需要定义属性的对象。prop(string | number | symbol) 需被定义或修改的属性名。descriptor 需被定义或修改的属性的描述符。
descriptorconfigurable: 仅当该属性的 configurabletrue 时,该属性才能够被改变,也能够被删除。默认为 falseenumerable: 仅当该属性的 enumerabletrue 时,该属性才能够出现在对象的枚举属性中。默认为 falsevalue: 该属性对应的值。可以是任何有效的 JavaScript 值(数值,对象,函数等)。默认为 undefinedwritable: 仅当仅当该属性的 writabletrue 时,该属性才能被赋值运算符改变。默认为 falseget: 一个给属性提供 getter 的方法,如果没有 getter 则为 undefined。该方法返回值被用作属性值。undefinedset: 一个给属性提供 setter 的方法,如果没有 setter 则为 undefined。该方法将接受唯一参数,并将该参数的新值分配给该属性。默认为undefined
const o = {}
Object.defineProperty(o, "a", {
  value : 37,
  writable : true,
  enumerable : true,
  configurable : true
})
console.log(o);//{ a: 37 }
Object.defineProperties(obj, props) 在⼀个对象上定义⼀个或多个新的属性或修改现有属性,并返回该对象
const o = {}
Object.defineProperties(o, {
  a:{
    value : 37,
    writable : true,
    enumerable : true,
    configurable : true
  },
  b:{
    value : 38,
    writable : true,
    enumerable : true,
    configurable : true
  }
})

console.log(o);//{ a: 37, b: 38 }
3.2.2控制对象状态的方法 Object.preventExtensions() 防止对象扩展。
const person = {
  name:'lxj',
  age:'23'
}
Object.preventExtensions(person)
person.sex = '男'
console.log(person);//{ name: 'lxj', age: '23' }

Object.isExtensible() 判断对象是否可扩展。
const person = {
  name:'lxj',
  age:'23'
}
Object.preventExtensions(person)
console.log(Object.isExtensible(person))//false
Object.seal() 禁止对象新增属性,并将对象所有属性设置为不可配置。
const person = {
  name:'lxj',
  age:'23'
}
Object.seal(person)
person.name = 'zh'
console.log(person);//{ name: 'zh', age: '23' }
person.sex = '女'
console.log(person);//{ name: 'zh', age: '23' }

Object.seal() 是可写的,即可修改属性的值

Object.isSealed() 判断一个对象是否为密封, 是返回true 否则false。
const person = {
  name:'lxj',
  age:'23'
}
Object.seal(person)
console.log(Object.isSealed(person));//true
Object.freeze() 冻结一个对象。

一个被冻结的对象再也不能被修改;冻结了一个对象则不能向这个对象添加新的属性,不能删除已有属性, 不能修改该对象已有属性的可枚举性、可配置性、可写性,以及不能修改已有属性的值。此外,冻结一个对象后该对象的原型也不能被修改。

const person = {
  name:'lxj',
  age:'23'
}
Object.freeze(person)
person.name = 'zh'
person.sex = '1'
console.log(person);//{ name: 'lxj', age: '23' }
Object.isFrozen() 判断一个对象是否被冻结。
const person = {
  name:'lxj',
  age:'23'
}
Object.freeze(person)
console.log(Object.isFrozen(person));//true
3.2.3原型链相关方法 Object.create() 以一个对象为原型创建新的实例
// 原型对象
var A = {
  print: function () {
    console.log('hello');
  }
};

// 实例对象
var B = Object.create(A);

Object.getPrototypeOf(B) === A // true
B.print() // hello
B.print === A.print // true
Object.setPrototypeOf(obj, prop) 设置对象的原型 Object.getPrototypeOf(obj) 返回对象的原型
const person = {
  name:'lxj',
  showName(){
    console.log(this.name);
  }
}
const people = {}
Object.setPrototypeOf(people, person)
console.log(Object.getPrototypeOf(people) === person);//true
4.定义在原型上的方法

定义在原型上的方法即在Object.prototype上的方法,实例也可以访问到也叫作实例方法,主要有一下几个:

Object.prototype.valueOf():返回当前对象对应的值。Object.prototype.toString():将对象转为字符串并返回Object.prototype.toLocaleString():返回当前对象对应的本地字符串形式。Object.prototype.hasOwnProperty():判断某个属性是否为当前对象自身的属性,还是继承自原型对象的属性。Object.prototype.isPrototypeOf():判断当前对象是否为另一个对象的原型。Object.prototype.propertyIsEnumerable():判断某个属性是否可枚举。 4.1 Object.prototype.valueOf() 返回当前对象对应的值。
const obj = {}
// obj.valueOf() 默认返回本身
console.log(obj.valueOf() === obj);//true
// 用途:js 存在自动类型转换  自动类型转换时会调用这个方法
console.log(1 + obj);//1[object Object]

obj.valueOf = () =>{
  return 2
}
console.log(1+obj);//3
4.2 Object.prototype.toString() 将对象转为字符串并返回

toString 方法的作用是返回一个对象的字符串形式,默认情况下返回类型字符串。

const o1 = {}
o1.toString() // "[object Object]"

const o2 = {a:1};
o2.toString() // "[object Object]"

返回 [object Object] 并没有太大的用处,可以自定义 toString 方法得到想要的字符串形式

const obj = {};
obj.toString = function () {
  return 'hello';
};

obj + ' ' + 'world' // "hello world"

数组、字符串、函数、Date 对象都分别部署了自定义的toString方法,覆盖了Object.prototype.toString方法。

const obj = {
  name:'张三',
  age:22,
  sex:1
}
const arr = [1, 2, 3, 4]

const foo = function(){
  return 1
}
const str = 'hello world'
const date = new Date()
console.log(obj.toLocaleString());//[object Object]
console.log(str.toLocaleString());//hello world
console.log(arr.toLocaleString());//1,2,3,4
console.log(foo.toLocaleString());//function(){ return 1 }
console.log(date.toLocaleString());//2022-5-13 10:21:11
4.2.1 利用Object.prototype.toString方法判断数据类型

由于实例对象可能会自定义toString方法,覆盖掉Object.prototype.toString方法,所以为了得到类型字符串,直接使用Object.prototype.toString方法,通过函数的call方法,可以在任意值上调用这个方法,帮助我们判断这个值的类型。

  Object.prototype.toString.call(value)

上面代码表示对value这个值调用Object.prototype.toString方法。
不同数据类型的Object.prototype.toString方法返回值如下。

数值:返回[object Number]。字符串:返回[object String]。布尔值:返回[object Boolean]。undefined:返回[object Undefined]。null:返回[object Null]。数组:返回[object Array]。arguments 对象:返回[object Arguments]。函数:返回[object Function]。Error 对象:返回[object Error]。Date 对象:返回[object Date]。RegExp 对象:返回[object RegExp]。其他对象:返回[object Object]
Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"

利用这个特性,可以写出一个比typeof运算符更准确的类型判断函数。

const type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"

在上面这个type函数的基础上,还可以加上专门判断某种类型数据的方法。

const type = function (o){
  const s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

['Null',
 'Undefined',
 'Object',
 'Array',
 'String',
 'Number',
 'Boolean',
 'Function',
 'RegExp'
].forEach(function (t) {
  type['is' + t] = function (o) {
    return type(o) === t.toLowerCase();
  };
});

type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true
4.3 Object.prototype.toLocaleString() 将对象转换为本地字符串并返回

Object.prototype.toLocaleString方法与toString的返回结果相同,也是返回一个值的字符串形式。

const obj = {};
obj.toString(obj) // "[object Object]"
obj.toLocaleString(obj) // "[object Object]"

这个方法的主要作用是留出一个接口,让各种不同的对象实现自己版本的toLocaleString,用来返回针对某些地域的特定的值。

const person = {
  toString: function () {
    return 'Mark Smith';
  },
  toLocaleString: function () {
    return '马克史密斯';
  }
};

person.toString() // Mark Smith
person.toLocaleString() // 马克史密斯

目前,主要有三个对象自定义了toLocaleString方法,而且toLocaleString的返回值跟用户设定的所在地域相关。

Array.prototype.toLocaleString()Number.prototype.toLocaleString()Date.prototype.toLocaleString()
const arr = [1, 2, 3, 4]
const num  = 123
const date = new Date()
console.log(arr.toLocaleString());//1,2,3,4
console.log(num.toLocaleString());//123
console.log(date.toLocaleString());//2022-5-13 10:21:11
4.4 Object.prototype.hasOwnProperty(str) 判断一个对象自身是否有某个属性
const obj = {
  p: 123
};

obj.hasOwnProperty('p') // true
obj.hasOwnProperty('toString') // false

上面代码中,对象obj自身具有p属性,所以返回truetoString属性是继承的,所以返回false

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/944861.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存