Javascript OOP示例(构造函数版本)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript OOP示例(构造函数版本)相关的知识,希望对你有一定的参考价值。
This is a simple example of OOP in javascript, based off the highly popular Javascript "The Definitive Guide" book by David Flanagan. I will be expanding this example in the future, let me know what you'd like to see. Thanks!Note: You must have firebug for firefox to see the results of console.log()
/* Author: Alvin Crespo Topic: OOP in Javascript Reference: Javascript "The Definitive Reference" by David Flanagan NOTES: * Javascript does not support TRUE classes like Java, C++ and C# do. * It is possible to define pseudoclasses in Javascript. A Constructor Method: new Object () Object from Constructors: var array = new Array(12); var today = new Date(); * NEW operator must be followed by the invocation of a function * Function that is designed to be used with the NEW operator is called a constructor * Purpose of the constructor is to initialize a new object */ //Constructor Method //************************************************************************* //Define the constructor function Square(objectW,objectH){ //initializes by using the keyword THIS this.width = objectW; this.height = objectH; //this is how to add a method to a constructor this.area = function(){ console.log("Area as a property/function of Square: " + (this.width * this.height)); } //The above area function works but is not optimal, because each Square will the area as a property //no return statement } //Invoking the constructor to create Square objects //square1 = {width:2, height:4} var square1 = new Square(5,10); //calling a constructors method var sqArea1 = square1.area(); /* About Prototype Object ---------------------------- * Every javascript object includes an internal reference to another object, known as a prototype object */ //creating a prototype Square.prototype.LargerSide = function(){ var result = ''; //inheritance is automatic as part of the process of looking up a property value, thus // width and height can be used if(this.width > this.height){ result = "Width is Larger"; }else if(this.width == this.height){ result = "Width and Height are the same"; }else{ result = "Height is Larger"; } console.log("Area as a prototype/function of Square: " + result); }//end of LargerSide prototype for Square square1.LargerSide(); //*************************************************************************
以上是关于Javascript OOP示例(构造函数版本)的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript oop proto与prototype原型图
03JavaScript程序设计修炼之道_ JS进阶 OOP构造函数 2019-07/21-171247***0725-200514