JavaScript Objiect方法

对象方法

一、Object原型方法

Object构造函数对应的原型中有很多方法,比较实用,如下:

console.log(Object.prototype)

图示:
在这里插入图片描述

1、hasOwnProperty

用于判断某个对象是否具有某个自带属性。自带属性,指的是自身就有的,而非继承来的,语法:

对象.hasOwnProperty(非继承属性) // 返回布尔值,true表示是,false表示否

例:

function Person(name, age) {
   
    this.name = name
    this.age = age
}

Person.prototype.sex = '男'

var man = new Person('张三', 12)

console.log( man.hasOwnProperty('name') ); // true
console.log( man.hasOwnProperty('sex') ); // false
console.log( man.hasOwnProperty('height') ); // false

只有自己内非继承的属性才能返回true,继承的和不是自己的属性都是false。

2、isPrototypeOf

用于判断一个对象是否在另一个对象的原型链上。语法:

对象a.isPrototypeOf(对象b) // 判断对象a是否在对象b的原型链上,返回布尔值

例:

function Animal() {
   

}

var ani = new Animal()

function Bird() {
   

}

Bird.prototype = ani

var maque = new Bird()

console.log( Object.prototype.isPrototypeOf(maque) ); // true
console.log( ani.isPrototypeOf(maque) ); // true
var ani1 = new Animal()
console.log( ani1.isPrototypeOf(maque) ); // false

3、propertyIsEnumerable

用于判断某个属性是否可遍历,语法:

对象.propertyIsEnumerable(属性名) // 返回布尔值

例:

function Person(name, age) {
   
    this.name = name
    this.age = age
}

Person.prototype.sex = '男'

var man = new Person('张三', 12)

console.log( man.propertyIsEnumerable('name') ) // true - 自己的属性可以遍历
console.log( man.propertyIsEnumerable('sex') ) // false - 继承来的属性无法遍历

4、toString

用于将对象转成字符串,语法:

对象.toString() // 返回'[object Object]'

5、其他

toLocaleStringvalueOf没有实际的效果,是为了让子原型能具备这些方法,来实现不同类型数据的功能。

toLocaleString给不同的数据调用会得到不同的数据:(数字的这个方法可以实现千分位分割)

// 对象调用
var obj = {
   name: '张三', age: 123456}
console.log( obj.toLocaleString() ); // [object Object]

// 字符串调用
var str = 'abcdefg'
console.log( str.toLocaleString() );  // abcdefg

// 数字调用
var num = 123456789
console.log( num.toLocaleString() ); // 123,456,789

// 布尔值调用
var bool = true
console.log( bool.toLocaleString() ); // true

// 时间日期对象调用
var date = new Date()
console.log( date.toLocaleString() ); // 2022/11/4 09:20:01

只有数字和时间日期对象调用的时候,能起到作用,其他类型的数据调用后,会默认调用toString方法转成字符串而已。

valueOf给不同类型的对象调用功能是不同的:(时间日期对象可以通过他获取到时间戳)

// 对象调用
var obj = {
   name: '张三', age: 123456}
console.log( obj.valueOf() ); // {name: '张三', age: 123456}

// 字符串调用
var str = new String('abcdefg')
console.log( str.valueOf() );  // abcdefg

// 数字调用
var num = new Number(123456789)
console.log( num.valueOf() ); // 123456789

// 布尔值调用
var bool = new Boolean(true)
console.log( bool.valueOf() ); // true

// 时间日期对象调用
var date = new Date()
console.log( date.valueOf() ); // 1667525014847

时间日期对象调用能获取到时间戳,其他类型的对象调用,会得到具体的值,相当于console.log(数组/对象)的值

二、Object方法

Object本身也有一些实用的方法:

console.dir(Object)

图示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值