面向对象编程
ES5实现
function Star(uname, height, weight) {
this.uname = uname;
this.height = height;
this.weight = weight
this.say = function () {
console.log(`我是${this.uname},我身高${this.height}厘米,体重${this.weight}公斤`)
}
}
var ldh = new Star("刘德华", 174, 64)
ldh.say()
var lyf = new Star("刘亦菲", 170, 80)
lyf.say()
ES6实现
function Star(uname, height, weight) {
this.uname = uname;
this.height = height;
this.weight = weight
this.say = function () {
console.log(`我是${this.uname},我身高${this.height}厘米,体重${this.weight}公斤`)
}
}
var ldh = new Star("刘德华", 174, 64)
ldh.say()
var lyf = new Star("刘亦菲", 170, 80)
lyf.say()
定义一个构造函数Circle,里面有两个方法area和length,分别计算圆的面积和周长
class Circle {
constructor(r) {
this.r = r
}
//计算周长
length() {
return (2 * Math.PI * this.r).toFixed(2)
}
//计算面积
area() {
return (Math.PI * r ** 2).toFixed(2)
}
}
console.log(new Circle(4).length())
console.log(new Circle(4).area())
ES6继承
// 父类 Person
class Person {
constructor(uname, age) {
//属性
this.uname = uname;
this.age = age
}
//方法
say() {
return `我是${this.uname},我年龄${this.age}岁`
}
}
//子类Student
class Student extends Person {
constructor(uname, age) {
// this.uname = uname;
// this.age = age;
super(uname, age)
}
}
var s1 = new Student("小红", 18)
console.log(s1.say())
//子类Teacher
递归
在一个函数内部调用自身
function fun(){
fun()
}
/*****
* 递归:在函数内部调用自己
* 使用递归:一定要有退出条件
*
* ******/
var n = 1;
function fun() {
if (n > 6) return;
console.log("我喜欢写代码")
n++
fun()
}
fun()
求阶乘(案例)
// 求阶乘 5!=5*4*3*2*1
function fun(n) {
if (n == 1) return 1
return n * fun(n - 1)
}
fun(5)
斐波那契数列(案例)
1 1 2 3 5 8 13
n=1 2 3 4 5 6 7
function fun(n){
}
案例
- 在控制台输出1~1000中,所有能被5或者6整除的数字
var arr = []
function fn(n) {
if (n == 1) return n = 1
if (n % 5 == 0 || n % 6 == 0) {
arr.push(n)
}
console.log(n);
fn(n - 1)
}
fn(10)
console.log(arr);
- 用户输入一个数字n,计算1+2+3+4+.....n的和
function f(n){
if(n == 0) return 0
console.log(n );
return n + f(n-1)
}
console.log(f(5))
- 用户输入一个数字计算 3/2 + 4/3 + 5/4 + ...... +n+1 / n
function fn(n){
if(n<2) return alert('输入的数字不能小于2')
if(n==2) return 3/2
return (n+1)/n+fn(n-1)
}
console.log(fn(n));