JavaScript Objectの常用方法の整理
17970 ワード
1. , , ( , )
let obj = Object.create({a:'Object'},{b:{value:'create'}})
obj.__proto__.a === 'Object' // true
obj.b = 'Object';
console.log(obj.b); // create
2. 、 、
const obj2 = Object.create({}, {
key: {
value: 2,
writable: true, //
enumerable: true, //
configurable: true, //
}
})
:enumerable
for...in:
Object.keys():
JSON.stringify:
1.
var drillDefineProperty = {};
2.
Object.defineProperty(drillDefineProperty, 'foundDefineProperty', {
value: "learnDefineProperty",
writable: true,
enumerable: true,
configurable: true
})
console.info(drillDefineProperty.foundDefineProperty); // learnDefineProperty
3.
Object.defineProperty(drillDefineProperty, 'foundDefineProperty', {
writable: false
})
// writable false , foundDefineProperty
drillDefineProperty.foundDefineProperty = 'rewrite_learnDefineProperty';
// , 、 ~
console.log(drillDefineProperty.foundDefineProperty) // learnDefineProperty
4.
Object.defineProperty(drillDefineProperty, 'newAccessorProperty', {
set: function (value) {
this.otherProperty = value
},
get: () => {
return this.otherProperty;
},
enumerable: true,
configurable: true
})
:
1:
2:descriptor (value writable )(get set )
3:configurable false ,
Object.defineProperties(drillDefineProperty,{
'property1':{
value:true,
writable:true
},
'property2':{
value:'Holle defineProperties',
writable:false,
}
})
console.log('Object.defineProperties:',drillDefineProperty.property1) // true
console.log('Object.defineProperties:',drillDefineProperty.property2) // Holle defineProperties
:Object defineProperty defineProperties js , ,
getOwnPropertyDescriptor getOwnPropertyDescriptors 。
let array = ['a','b','c','d'];
let object = {name:'keys',age:18};
let arrLike = {0:'a',1:'b',2:'c'};
console.log(Object.keys(array)) // ['0','1','2','3']
console.log(Object.keys(object)) // ['name','age']
console.log(Object.keys(arrLike)) //['0','1','2']
を含みません. let array = ['a','b','c','d'];
let object = {name:'keys',age:18};
let arrLike = {0:'a',1:'b',2:'c'};
console.log(Object.values(array)) // ["a", "b", "c", "d"]
console.log(Object.values(object)) // ["keys", 18]
console.log(Object.values(arrLike)) // ["a", "b", "c"]
を含まない. :object.assign(target,source,source1) , (source) , (target)。
, ( ), (enumerable:false)
const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };
console.log(Object.assign(target, source1, source2)) // {a: 1, b: 2, c: 3}
//
let object = { a: 1 };
console.log(Object.assign(object, undefined) === object) // true
console.log(Object.assign(object, null) === object) // true
console.log(Object.assign([1, 2, 3], [3, 4])) // [3, 4, 3]
// Object.assign(); ,
const obj1 = { a: { b: 1 } };
const obj2 = Object.assign({}, obj1);
obj1.a.b = 2;
console.log(obj2.a.b) // 2
obj2.a.b = 3;
console.log(obj1.a.b) // 3
const prototype1 = {}
const object = Object.create(prototype1);
console.log(Object.getPrototypeOf(object) === prototype1); // true
//
// Object.getPrototypeOf(Object) Object.prototype
console.log(Object.getPrototypeOf(Object) === Object.prototype ) // false
console.log(Object.getPrototypeOf(Object) === Function.prototype) // true
const object = { a: 1 }, proto = { b: 2 };
console.log(Object.setPrototypeOf(object, proto)) // {a: 1} {a: 1__proto__: b: 2__proto__: Object}
console.log(object.__proto__ === proto) // true
を設定します. let creativeObject = Object.create({},{
getFoo:{
value:function (){return this.foo},
enumerable:false, //
}
})
creativeObject.foo = 11;
console.log(Object.getOwnPropertyNames(creativeObject).sort()) // ["foo", "getFoo"]
を含んでいます. let obj = { foo: 123 };
console.log(Object.getOwnPropertyDescriptor(obj,'foo'))
// {value: 123, writable: true, enumerable: true, configurable: true}
を取得する. const obj = {
foo: 123,
get bar() { return 'abs' }
}
console.dir(Object.getOwnPropertyDescriptors(obj));
/*
{ foo:{ value: 123,
writable: true,
enumerable: true,
configurable: true },
bar:{ get: [Function: bar],
set: undefined,
enumerable: true,
configurable: true }
}
*/
//
Object.assign() // , , ,
Object.create() // , getPrototypeOf , getOwnPropertyDescriptors
console.log(Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
))
を返します. const obj = {foo:'bar',baz:42};
console.log(JSON.stringify(Object.entries(obj),null,2)); // [ ['foo', 'bar'], ['baz', 42] ]
const obj1 = {0:'a',1:'b',2:'c'};
console.log(Object.entries(obj1)) // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
console.log(Object.entries('abc')) //[['0', 'a'], ['1', 'b'], ['2', 'c']]
console.log(Object.entries(100) ) // []
console.log(Object.is('foo','foo')) // true
console.log(Object.is({},{})) // false
console.log(Object.is(+12,-12)); // false
console.log(Object.is(NaN === NaN)) // false
let empty = {};
console.log(Object.isExtensible(empty)) // true
empty.a = 1;
console.log(empty) // {a:1}
//
Object.preventExtensions(empty);
console.log(Object.isExtensible(empty)) // false
empty.b = 2; // , ( ~)
empty.a = 5; //
delete empty.a; // {}
console.log(empty)
:
1. preventExtensions ,
2.
3. , , TypeError ( )。
4.Object.preventExtensions , 。
であるかどうかを判定する. // , , 、 、
// 1、 seal
var sealObject1 = {b:1};
sealObject1.d = 2; //
var sealObject2 = Object.seal(sealObject1);
console.log(sealObject2 === sealObject1) // true ,
Object.isSealed(sealObject1) // true
sealObject1.b = 3;
console.log(sealObject1) // {b: 3, d: 2}
sealObject1.f = 222; // , f
delete sealObject1.b // , b
// 2、 isSealed
let isSealed = {};
console.log(Object.isSealed(isSealed)) // false
// Object.preventExtensions
Object.preventExtensions(isSealed);
console.log(Object.isSealed(isSealed)) // true
// ?
let isNullSealed = {value:1};
Object.preventExtensions(isNullSealed);
console.log(Object.isSealed(isNullSealed)) // false
// value (configurable true) , , :
let allocation = {value:111}
Object.preventExtensions(allocation);
Object.defineProperty(allocation,'value',{configurable:false})
console.log(Object.isSealed(allocation));// true
// :
1. ,
2. ,
3.
4. , TypeError ( )
// freeze & isFrozen
// , , , 、 、 。 。
// 1. freeze
let freeze = {a:1};
freeze.b = 2; // b
console.log(Object.freeze(freeze)); // {a: 1, b: 2}
console.log(Object.isFrozen(freeze) ) // true
freeze.a = 2 // a
freeze.c = 5; // c
delete freeze.b // b
console.log(freeze) // // {a: 1, b: 2}
// 2. isfreeze
let isFrozen = {a:1};
isFrozen.b = 2; //
Object.preventExtensions(isFrozen);
Object.defineProperties(isFrozen,{
a:{configurable:false,writable:false},
b:{configurable:false,writable:false}
})
console.log(Object.isFrozen(isFrozen) ) //
:
1.
2. , , ( )
3. , ( getter setter) ( , )。
4. , , 。
// :
(function () {
let obj = {
internal: {}
};
Object.freeze(obj); //
obj.internal.a = 'aValue';
// , ,
function deepFreeze(o) {
var prop, propKey;
Object.freeze(o);//
for (propKey in o) {
prop = o[propKey];
if (!o.hasOwnProperty(propKey) || !(typeof prop === 'object') || Object.isFrozen(prop)) {
continue;
}
deepFreeze(prop); //
}
}
deepFreeze(obj);
obj.internal.b = 'bValue'; //
console.log(obj.internal.b) // undefined
}())
// Object.hasOwnProperty(); ,
let hop = { a: 1 };
console.log(hop.hasOwnProperty('a')) // true
console.log(hop.hasOwnProperty('b')) // false
console.log(hop.hasOwnProperty('toString')); // false
// , :
var buz = {
foo: 'stack'
}
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.table({ key: name, value: buz[name] })
} else {
console.log(name);
}
}
// Object.isPrototypeOf();
function Foo(){};
function Bar(){};
function Baz(){};
Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);
var baz = new Baz();
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
を返します. // obj.propertyIsEnumerable(prop) prop
// 1.
var ordinary = {};
var contrast = [];
ordinary.porp = 'is enumerable';
contrast[0] = 'is enumerable';
console.log(ordinary.propertyIsEnumerable('porp'));
console.log(contrast.propertyIsEnumerable(0));
// 2.
var browser = ['is enumerable'];
console.log(browser.propertyIsEnumerable(0)); // true
console.log(Math.propertyIsEnumerable('random')); // false
console.log(this.propertyIsEnumerable('Math')); // false
//3. ( propertyIsEnumberable )
var fu = function () {
this.prop = '123';
}
fu.prototype = { prototypeProp: true };
var o = new fu();
console.log(o.propertyIsEnumerable('prop')); // true
console.log(o.propertyIsEnumerable('prototypeProp')) // false
を返す必要がある. // Object.caller()
function test() {
if (test.caller === null) {
alert('Javascript test() ')
} else {
alert(test.caller + ' test() ')
}
}
test(); // Javasript test()
function callTest() {
test();
}
callTest(); // function callTest(){ test(); } test()
function callTest2() {
// setTimeout() setInterval()
setTimeout(test, 500); // JavaScript test()
}
callTest2();
// :js valueOf() toString() , , ;
// ,JavaScript valueOf()
const o = { a: 21, valueOf: function () { return '234234' } };
console.log(Number(o)) // 234234
//
const o2 = {
x: 1,
valueOf: function () {
return this.x++;
}
}
if (o2 == 1 && o2 == 2 && o2 == 3) {
console.log('down');
console.log(o2.x);
} else {
console.log('faild')
}
// Array :
var array = ['CodePlayer', true, 12, -5];
console.log(array.valueOf() === array);
// Date: 1970 1 1
var date = new Date(2013, 7, 18, 23, 11, 59, 230);
console.log(date.valueOf()) // 1376838719230
// Number:
var num = 15.23423;
console.log(num.valueOf()) // 15.23423
// : true false
var bool = true;
console.log(bool.valueOf() === bool) // true
// new boolean
var newBool = new Boolean(true);
// valueOf() true ,
console.log(newBool.valueOf() == newBool); // true
// , , boolean , object
console.log(newBool.valueOf() === newBool); // false
// Function :
function foo() { }
console.log(foo.valueOf() === foo) // true
var foo2 = new Function("x", "y", 'return x + y');
console.log(foo2.valueOf() === foo2) // true
// Object :
var obj = {name:' ',age:18};
console.log(obj.valueOf() === obj) // true
// String
var str = 'www.zjwas.com';
console.log(str.valueOf() === str) // true
// new
var str2 = new String('http://123.com');
// , , , string , object
console.log(str2.valueOf === str2) // false
// Object.getOwnPropertySymbols() Symbol
var obj = {};
var a = Symbol('a');
var b = Symbol.for('b');
obj[a] = 'localSymbol';
obj[b] = 'golablSymbol';
var objectSymbol = Object.getOwnPropertySymbols(obj);
console.log(objectSymbol.length) // 2
console.log(objectSymbol) // [Symbol(a), Symbol(b)]
console.log(objectSymbol[0]) // Symbol(a)
// ,toLocaleString
console.log((new Date).toString()) // Fri Jan 15 2021 15:13:06 GMT+0800 ( )
console.log((new Date).toLocaleDateString()); // 2021/1/15
console.log((new Date).toLocaleString()) // 2021/1/15 3:17:19
console.log((new Date).toLocaleTimeString()) // 3:17:50
console.log((new Date).toTimeString()) // GMT+0800 ( )
console.log((new Date).toUTCString()) // Fri, 15 Jan 2021 07:18:35 GMT
console.log((new Date).toISOString()) // 2021-01-15T07:19:03.860Z
console.log((new Date).valueOf()) // 1610695165279
// ,toLocaleString
console.log((Date.parse(new Date())).toLocaleString()) // 1,610,695,344,000
console.log((Date.parse(new Date())).toString() ) // 1610695371000
Object.length //1