Home  >  Article  >  Web Front-end  >  JavaScript object-oriented definition member method instance analysis

JavaScript object-oriented definition member method instance analysis

韦小宝
韦小宝Original
2017-11-30 09:01:041454browse

This article analyzes the example of javascriptobject-orienteddefinitionmember method, and JavaScriptobject-oriented definition Students who are not familiar with member methods can take a look and learn about JavaScript!

javascript is object-oriented and defines member methods 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.age+"岁");
 }
}
var p1 = new Person("王美人",24);
p1.show();
</script>

Description:
(1) The constructor is used here;
(2) this.show=function() is a definition method that makes every instantiated object have this method. If you need to own an instantiated object separately, you can write the function externally and then pass it over, as shown in the following example;
(3) There can also be parameters in function() of this.show.


The function is defined externally
Because the properties and methods of the javascript object are dynamically added, it can be defined like this :

<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("王美人",24);
p1.show1 = show;//注意,函数后面带()与不带()的区别。带括号表示将结果给p1.show1,而不带括号表示将该函数给p1.show1。
p1.show1();
</script>

Or it can also be defined like this:

p1.show1 = function show(){..................}

The above is all the content of the analysis of object-oriented definition member methods in JavaScript. I hope it can help students understand JavaScript.

Related recommendations:

Specific analysis of JavaScript object-oriented basics and this pointing issues

##javascript object-oriented property function usage

JavaScript Object-Oriented Programming (Object Creation)

The above is the detailed content of JavaScript object-oriented definition member method instance analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn