如何在JavaScript中定义OOP类? [英] How do you define an OOP class in JavaScript?

查看:116
本文介绍了如何在JavaScript中定义OOP类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的观察,我正在阅读的关于JavaScript的书说明有一个带有JavaScript的OOP?它并没有说太多,我的意思是没有解释如何定义一个类。有人可以给我一个样本片段吗?

Based on my observation, the book that I am reading about JavaScript states that there's an OOP with JavaScript? It doesn't tell much about it, I mean it wasn't explained how to define a class. Can someone give me a sample snippet?

谢谢

推荐答案

以下代码段可以帮助您入门JavaScript的无类,基于实例的对象:

The following snippet may help you getting started with JavaScript's class-less, instance-based objects:

function getArea() {  
   return (this.radius * this.radius * 3.14);  
}  

function getCircumference() {  
   var diameter = this.radius * 2;  
   var circumference = diameter * 3.14;  
   return circumference;  
}

function Circle(radius) {  
   this.radius = radius;  
   this.getArea = getArea;  
   this.getCircumference = getCircumference;  
}

var bigCircle = new Circle(100);  
var smallCircle = new Circle(2);

alert(bigCircle.getArea());            // displays 31400  
alert(bigCircle.getCircumference());   // displays 618  
alert(smallCircle.getArea());          // displays 12.56  
alert(smallCircle.getCircumference()); // displays 12.56

示例来自: SitePoint - JavaScript面向对象编程

这篇关于如何在JavaScript中定义OOP类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆