看代码学编程之js高级语法

时间:2021-12-02 09:16:18

正则

看代码学编程之js高级语法

看代码学编程之js高级语法

看代码学编程之js高级语法

看代码学编程之js高级语法

看代码学编程之js高级语法

对象

function log(str) {
if(typeof str == 'object'){
document.write(JSON.stringify(str));

}else {
document.write(str);
}

document.write('<hr />');
}

try {
var obj = {};
obj.x = 3;
obj.y = 5;
function foo() {
}

foo.prototype.z = 3;
var o = new foo();
log(o.z);//3
log(foo.hasOwnProperty('z'));//false
obj.z = 7;
obj.x = 7;
log(obj.hasOwnProperty('z'));//true
//obj.prototype.z = 5; //报错
delete obj.z;
log(obj.z); //undefinded
o.z=6;
log(o.z);//6
delete o.z;
log(o.z);//3
delete o.z;//只能删除本对象的属性,不能删除原型链上的属性why?
log(Object.getOwnPropertyDescriptor(o,"z"));//{"writable":false,"enumerable":true,"configurable":false}
//原型链上的属性权限很低,只有可列出属性的权限,故不能删除
Object.defineProperty(o, "z", { writable: true });
delete o.z;//给权限以后即可删除
log(o.z);//undefinded
//未实例化的函数实体不具有属性描述
log(Object.getOwnPropertyDescriptor(foo,"z"));//undefined
log(obj.x);//7
//自定义键值对对象的属性默认具有最高权限
log(Object.getOwnPropertyDescriptor(obj,"x"));//{"writable":true,"enumerable":true,"configurable":true}

Object.defineProperty(obj, "y", { writable: false });
log(Object.getOwnPropertyDescriptor(obj,"y"));//{"value":5,"writable":false,"enumerable":true,"configurable":true}
Object.defineProperty(obj, "y", { enumerable: false });
log(Object.getOwnPropertyDescriptor(obj,"y"));//{"value":5,"writable":false,"enumerable":false,"configurable":true}
// Object.defineProperty(o, "z", { enumerable: true });
log('-----------------------------------------------------------------');

/**
* 对象创建
*/
var obj1 = Object.create({x:1});
log(obj1.x);//1
log(Object.getOwnPropertyDescriptor(obj1,'x'));//undefinded why?
console.log(obj1);
console.log(o);
log(obj1.__proto__.constructor);//function Object() { [native code] }
log(obj.__proto__.constructor);//function Object() { [native code] }
log(o.__proto__.constructor);//function foo() { }
log(obj1.hasOwnProperty('x'));//false
//创建不带属性的空对象
var obj2 = Object.create(null);
console.log(obj2);//Object {}No Properties 不带任何属性
// console.log(obj2.toString());//undefinded
var globalVar1 =1;

log(Object.getOwnPropertyDescriptor(window,'globalVar1'));//{"value":1,"writable":true,"enumerable":true,"configurable":false}
log(delete globalVar);//false 特例
globalVar2 = 2;
log(Object.getOwnPropertyDescriptor(window,'globalVar2'));//{"value":2,"writable":true,"enumerable":true,"configurable":true}
log(delete globalVar);//true 特例
obj2.x=111;
log(Object.getOwnPropertyDescriptor(obj2,'x'));//{"value":2,"writable":true,"enumerable":true,"configurable":true}
Object.defineProperty(obj2,'x',{'writable':false});
log(delete obj2.x);//true writable跟删除权限无关,configurable决定删除权限
log(delete foo);//false
(function () {
var aa =1;
log(delete aa);//false
})();

看代码学编程之js高级语法

看代码学编程之js高级语法