JavaScript_object Basic Introduction of Required Read

  • 2021-06-28 10:32:39
  • OfStack

Previously, when writing Java, it was a bit confusing, mostly using jQuery, but the principle is not clear yet. In the last period of time, when learning JavaScript in the system, what are the problems or errors? Please point out, thanks a lot...

Base class for all Object classes

var obj = new Object();
var obj = {}; //Instantiate Object
There are two ways to set properties on an object:

1. How to use direct quantities: objects, attributes/methods, which are intuitive and easy to understand

obj.name ='Zhang 3';
obj.age = 20;
obj.sex ='male';
obj.say = function(){
alert("hello World");
}

2. Use the'[]'method: object. ['property/method'], when using this method, parentheses must be enclosed with'' or'', which is more rigorous

obj['birthday'] = '1989-08-07';

Get the properties or methods of an object: object. Property name/method
alert (obj.name); //Zhang 3
alert(obj.age); // 20
obj.say(); // hello World

The delete operator deletes an object's properties or methods
delete obj.age;
delete obj.say;
alert(obj.age); //undified
alert(obj.sex); //20
obj.say(); //Error, function deleted

Traverse an js object, for in statement

for(var attr in obj){
alert (attr +':'+ obj [attr]); //The key-value pairs in the array are printed sequentially, the primary value, if undified is derived from the object.property
}

Constructor Save Object Creation Function
alert(obj.constructor);
var o = [];
alert(o.constructor);

hasOwnProperty (propertyName) is used to detect whether a given attribute exists in an object, returning the boolean type, which is sometimes used in projects and should be noted
var i = {};
i.sex ='man';
alert(i.hasOwnProperty('sex')); //true
alert(i.hasOwnProperty('age')); //false

propertyIsEnumerable (propertyName) detects whether a given attribute can be enumerated by for in and returns boolean
alert (i.propertyIsEnumerable ('age')); //This property is not defined above false


Related articles: