This article analyzes the javascript object-oriented member method. Share it for your reference. The details are as follows:
JavaScript object-oriented, defines member methods as follows:
Copy the code as follows:<script language="javascript" type="text/javascript">
function Person(name,age){
this.name = name;
this.age = age;
this.show = function(){
document.write(this.name+"This year"+this.age+"year");
}
}
var p1 = new Person("Beauty Wang",24);
p1.show();
</script>
illustrate:
(1) The constructor is used here;
(2) This definition method is this.show=function(), so that each instantiated object has this method. If an instantiated object needs to be owned separately, you can write the function outside and pass it over, as in the following example;
(3) There can also be parameters in function() of this.show.
Functions are defined externally
Because the properties and methods of javascript objects are dynamically added, they can be defined as follows:
Copy the code as follows:<script language="javascript" type="text/javascript">
function Person(name,age){
this.name = name;
this.age = age;
}
function show(){
window.alert("hello,"+this.name);
}
var p1 = new Person("Beauty Wang",24);
p1.show1 = show;//Note that the function has the difference between () and without (). With brackets, it means giving the result to p1.show1, while without brackets means giving the function to p1.show1.
p1.show1();
</script>
Or you can also define it like this: the copy code code is as follows: p1.show1 = function show(){............}
I hope this article will be helpful to everyone's JavaScript programming.