对象方法
一、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、其他
toLocaleString
和valueOf
没有实际的效果,是为了让子原型能具备这些方法,来实现不同类型数据的功能。
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)
图示: