程序员

背熟它,你也能用面向对象,写出优雅的JavaScript代码

2018-10-12  本文已影响0人  一码一故事

原始类型与引用类型

注:这里的JavaScript代码参考了《JavaScript面向对象精要》,非常好的一本书,建议有时间的同学可以买来看看。

1、原始类型

JAVA JavaScript 说明
boolean boolean
char number JavaScript里面number包含了所有的数值型,包括整数和浮点数
byte number
short number
int number
long number
float number
double number
string JAVA中字符串是对象,不是原始类型
null null
undefined JAVA中没有对应的类型

这里要注意的是,java和JavaScript对原始类型,都有对应的封装的引用类型,比如java里面的int对应的引用类型为Integer,封装类可以赋予原始类型很多方法,可以帮助你更好地使用它。

// 原始类型
int i1 = 1;
// 封装后的引用类型
Integer i2 = 2;
// 引用类型本质上是个对象,包含有方法
//下面的toString就是Integer的方法,原始类型int是没有方法的
System.out.println(i2.toString());

JavaScript的原始类型,也有对应封装的引用类型,只是更为隐蔽

const name = "Sam";
const firstChar = name.charAt(0);
console.log(firstChar); //此处会打印出字符S

上面的代码实际上有个隐式转换的过程,等价于下面的代码

const name = "Sam";
let temp = new String(name);//此处做了一个隐式转换,产生了一个临时的String对象
const firstChar = temp.charAt(0);//此处调用了临时对象的charAt方法
temp = null;//释放临时对象
console.log(firstChar); //此处会打印出字符S

从这里来看,JavaScript和Java极其类似,没有太大区别,只要我们熟悉了对应的代码格式,我们也能使用面向对象的方法,写出优雅的JavaScript代码。

2、引用类型

两种语言中,引用类型本质上是一样的,除了我们自己定义的引用类型外,系统还有一些內建的引用类型,下面举一些具体的例子,比如Date

JAVA JavaScript
java.util.Date Date
java.util.ArrayList Array

3、函数重载

JavaScript中,函数重载可以自己根据参数类型以及参数个数自己处理。

JAVA:

private static void sayMessage(String msg) {
    System.out.println(msg);
}

private static void sayMessage() {
    System.out.println("Default message");
}

JavaScript:


function sayMessage(message) {
    if (arguments.length === 0) {
        message = 'Default message';
    }
    console.log(message);
}

4、创建对象

JAVA:

class Person {
    public Person(String name) {
        this.name = name;
    }
    private String name;
}
Person p = new Person("Sam");

JavaScript使用字面量:

const p1 = {
    name: 'Sam'
};
console.log(p1.name);

JavaScript使用Object构造方法:

const p2 = new Object();
p2.name = 'Sam';
console.log(p2.name);

JavaScript使用自定义的构造方法:

function Person(name) {
    this.name = name;
}
const p3 = new Person('Sam');
console.log(p3.name);

JavaScript使用ES6:

class PersonEs6 {
    constructor(name) {
        this.name = name;
    }
}
const p4 = new PersonEs6('Sam');
console.log(p4.name);

可以看到新一代的JavaScript标准,已经和Java非常类似了,以后我们如果用ES6来写JavaScript会更加得心应手。

4、动态修改对象属性

JAVA不支持对象属性的动态修改,这里的例子是针对JavaScript而言

class PersonEs6 {
    constructor(name) {
        this.name = name;
    }
}
const p4 = new PersonEs6('Sam');
p4.age = 10;//动态增加age
console.log(p4.age);
class PersonEs6 {
    constructor(name) {
        this.name = name;
    }
}
const p4 = new PersonEs6('Sam');
delete p4.name;//删除属性name
console.log(p4.name);

5、遍历对象属性

Java中,属性遍历可以使用反射机制进行

class Person {
    public Person(String name) {
        this.name = name;
    }
    private String name;
}
Person p = new Person("Sam");
for (Field field : p.getClass().getDeclaredFields()) {
    field.setAccessible(true);
    System.out.println(field.getName() + ":" + field.get(p));
}

JavaScript:

class PersonEs6 {
    constructor(name) {
        this.name = name;
    }
}
const p4 = new PersonEs6('Sam', 10);
//使用for in会遍历原型属性
for (const property in p4) {
    console.log(`属性名称:${property},属性值:${p4[property]}`)
}

6、继承

JAVA:

class Rectangle {
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    public int getArea() {
        return this.length * this.width;
    }

    @Override
    public String toString() {
        return String.format("Rectangle: %d X %d", this.length, this.width);
    }

    protected int length;
    protected int width;
}

class Square extends Rectangle {
    public Square(int size) {
        super(size, size);
    }

    @Override
    public String toString() {
        return String.format("Square: %d X %d", this.length, this.width);
    }

}

JavaScript定义类【长方形】:

function Rectangle(length, width) {
    this.length = length;
    this.width = width;
}

//定义该类的方法
Rectangle.prototype.getArea = function () {
    return this.length * this.width;
};
Rectangle.prototype.toString = function () {
    return `Rectangle: ${this.length} X ${this.width}`;
};
const r1 = new Rectangle(3, 2);
console.log(r1.getArea());
console.log(r1.toString());

// 【正方形】继承自长方形
function Square(size) {
    Rectangle.call(this, size, size);
}

Square.prototype = Object.create(Rectangle.prototype, {
    constructor: {
        configurable: true,
        enumerable: true,
        value: Square,
        writable: true,
    }
});
//重写父类的toString方法
Square.prototype.toString = function () {
    return `Square: ${this.length} X ${this.width}`;
};
const s1 = new Square(3);
console.log(s1.getArea());
console.log(s1.toString());

ES6定义类【长方形】:

class Rectangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
    }

    getArea() {
        return this.length * this.width;
    }

    // 重写父类的toString方法
    toString() {
        return `Rectangle: ${this.length} X ${this.width}`;
    };
}

const r1 = new Rectangle(3, 2);
console.log(r1.getArea());
console.log(r1.toString());

// 【正方形】继承自长方形
class Square extends Rectangle {
    constructor(size) {
        super(size, size);
    }

    // 重写父类的toString方法
    toString() {
        return `Rectangle: ${this.length} X ${this.width}`;
    };
}

const s1 = new Square(3);
console.log(s1.getArea());
console.log(s1.toString());

可以看出ES6语法越来越接近Java

上一篇 下一篇

猜你喜欢

热点阅读