Home  >  Article  >  Web Front-end  >  A simple implementation of Javascript to create classes and dynamically add properties and methods

A simple implementation of Javascript to create classes and dynamically add properties and methods

高洛峰
高洛峰Original
2016-12-09 15:19:27957browse

JavaScript is a strong object-oriented language that supports adding properties and methods after creating an instance. Although it is a small trick, it is easy to forget when using it. I wrote a small example today and recorded it here for reference only. .

function MyClass()
{ 
  //This function is same as a constructer 
  alert("New Object Created"); 
}
//Creating Object 
var MyObject = new MyClass (); 
NewObject.prototype = 
{ 
  //Adding Method named "MyMethod" 
  MyMethod: function(){alert("My Method");} , 
   
  //Adding property named "MyProperty" 
  MyProperty: "My Property" 
}
  
//Calling Method 
MyObject.MyMethod(); 
  
//Assigning Property 
MyObject.MyProperty = "My Property Value changed";


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