JavaScript(3)——Object-Oriented Design

本文介绍了一个简单的面向对象编程示例,通过定义一个笑脸类并为其添加绘制和说话的方法,展示了如何创建多个实例并对它们进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己定义函数

var Winston = function(nickname, age, x, y) {
    this.nickname = nickname;
    this.age = age + "yrs old";
    this.x = x;
    this.y = y;
};

引用以定义函数

var winstonTeen = new Winston("Winsteen", 15, 20, 50);
var winstonAdult = new Winston("Mr. Winst-a-lot", 30, 229, 50);

 面向对象编程

/*
It is very hard for me to do it at the first time
*/

/*
var faceObj = {
    centerX: 100, 
    centerY: 100
};
*/

//Above code can be instead by next code
var SmileyFace = function(centerX, centerY) {
    this.centerX = centerX;
    this.centerY = centerY;
};

/*
var drawSmiley = function(faceObj) {
    fill(255, 234, 0);
    ellipse(faceObj.centerX, faceObj.centerY, 150, 150);
    fill(0, 0, 0);
    ellipse(faceObj.centerX-30, faceObj.centerY-30, 20, 20); 
    ellipse(faceObj.centerX+30, faceObj.centerY-30, 20, 20); 
    noFill(); 
    strokeWeight(3);
    arc(faceObj.centerX, faceObj.centerY+10, 64, 40, 0, 180);
};
*/

//the above code can be instead by next code
SmileyFace.prototype.draw = function() {
    fill(255, 234, 0);
    ellipse(this.centerX, this.centerY, 150, 150);
    fill(0, 0, 0);
    ellipse(this.centerX-30, this.centerY-30, 20, 20); 
    ellipse(this.centerX+30, this.centerY-30, 20, 20); 
    noFill(); 
    strokeWeight(3);
    arc(this.centerX, this.centerY+10, 64, 40, 0, 180);    
};

SmileyFace.prototype.speak = function(myString) {
    text(myString, this.centerX-30, this.centerY+90);
};

var firstFace = new SmileyFace(100, 100);
var secondFace = new SmileyFace(100, 300);
var thirdFace = new SmileyFace(300, 300);
var fourthFace = new SmileyFace(300, 100);

//drawSmiley(faceObj);
firstFace.draw();
firstFace.speak("I'm first brother!"); 
//drawSmiley(secondFace);
secondFace.draw();
secondFace.speak("I'm second brother!");
thirdFace.draw();
thirdFace.speak("I'm third brother!!!");
fourthFace.draw();
fourthFace.speak("I'm fourth brother!");

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/8358578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值