Prototypes/Objects in javascript

1.javascript creates object new prototype chain

function foo(){
        }
        foo.prototype.z=3;
        var obj=new foo();
        obj.x=1;
        obj.y=2;
        obj.z=5;
        console.log(obj.x);//1
        console.log(obj.z);//5
        console.log(typeof obj.toString());//string type
        console.log(obj.hasOwnProperty("z"));//false
        for(var x in obj){
            console.log(obj[x]);//1  2  5
        }
        obj.z=undefined;
        console.log(obj.z);//5
        console.log(delete obj.z);//true, delete directly copied variables
        console.log(obj.z);//3
        console.log(delete foo.prototype.z);//true
        console.log(obj.z);//undefined

As shown in the code above, if an attribute in an object is assigned a value by direct assignment, the output is not an attribute added to the prototype chain, and the value of obj.z is 5, but if there is no obj.z=5; the output is 3, because the value of the attribute added by prototype, that is, the value on the prototype chain, is accessed.However, if you want to access the properties on the prototype chain if you have already assigned a value, you must delete the variable with the delete operator, and then access the values on the prototype chain again.

2. Object creation-Object.create()

var obj=Object.create({x:1});
console.log(obj.x);//Properties on Prototype Chain
console.log(typeof obj.toString);//function
        console.log(obj.hasOwnProperty("x"));//false

var obj1=Object.create(null);
console.log(typeofobj1.toString);//undefined

As shown in the code above, you canObject.createCreating an object by () is equivalent to creating an attribute by prototype chain, with the newly created object obj's prototype pointing to the created parameter, which is inherited from the prototype chain, not the attribute of the object itself.

3.javascript property acquisition

var obj={};
console.log(obj.y);//undefined
console.log(obj.y.z);//Syntax error typeError
obj.y.z=3;
console.log(obj.y.z);

4.javascript attribute deletion

var person={age:28,title:'fe'};
console.log(delete person.age);//true
console.log(delete person["title"]);//true
console.log(person.age);//undefined
console.log(delete person.age);//true
console.log(person.age); //undefined
console.log(delete Object.prototype);//false

var descriptor=Object.getOwnPropertyDescriptor(Object,'prototype');
descriptor.configurable;//false

As shown in the figure above, some attributes are not allowed to be deleted, such asObject.prototype, look at the last two lines of code in the figure above, and getObject.prototypeProperty, and its configurable value is false, so delete is not allowed

Tags: Attribute Javascript

Posted on Mon, 01 Jun 2020 10:14:53 -0700 by James25