References to properties and methods
1) In terms of visibility:
Private properties and methods can only be referenced within the object.
Instance properties and methods can be used anywhere, but must be referenced through objects.
Class properties and methods can be used anywhere, but cannot be referenced through instances of objects (this is different from Java, in which static members can be accessed through instances).
2) From the object level:
is similar to the reference of Java beans and can be referenced in depth.
Several ways:
Simple property: obj.propertyName
Object property: obj.innerObj.propertyName
Index property: obj.propertyName[index ]
Similar to above for deeper references.
3) In terms of definition:
Attributes defined through index must be referenced through index.
Attributes defined through non-index methods must be referenced through normal methods.
Also note: Object methods cannot be defined through index.
Dynamic addition and deletion of attributes and methods
1) For an instantiated object, we can dynamically add and delete its attributes and methods. The syntax is as follows ( Assume that the object instance is obj):
Dynamicly add object properties
obj.newPropertyName=value;
Dynamicly add object methods
obj.newMethodName=method Or =function(arg1,…,argN){}
Dynamic deletion of object properties
delete obj.propertyName
Dynamic deletion of object methods
delete obj .methodName
2) Example:
function User(name){ this.name=name; this.age=18; } var user=new User(“user1”); user.sister=“susan”; alert(user.sister);//运行通过 delete user.sister; alert(user.sister);//报错:对象不支持该属性 user.getMotherName=function(){return “mary”;} alert(user.getMotherName());//运行通过 delete user.getMotherName; alert(user.getMotherName());//报错:对象不支持该方法
The above is the detailed content of Detailed explanation of javascript attribute and method reference, addition and deletion of instances. For more information, please follow other related articles on the PHP Chinese website!