es5
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
es5都能做得到。es6的作用是,让对象原型的写法更加看得懂、更像面向对象编程。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
上面就是定义了一个“类”。
constructor(): 构造方法
this: 实例对象
Class写法,ES5的构造函数Point是一致的。
Point类除了构造方法,还定义了一个toString()方法。定义toString()方法,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
类的数据类型就是函数,类本身就指向构造函数。
使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。
class Bar {
doStuff() {
console.log('stuff');
}
}
问1:String s = new String("abc") 共有几个对象? 2个
一个new本身 一个是“abc“
问2:String s = new String("abc")共创建了几个对象?1个或者2个
就看abc有没有提前创建出来了
如果之前提前创建了abc了,那么String s = new String("abc"),就只创建了一个,因为abc不用单独再创建了,直接共享过来即可。
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello"+"world";
String s5 = s1+"world";
String s6 = s1+s2;
System.out.println(s3==s4);//true
System.out.println(s3==s5);//false
System.out.println(s3==s6);//false
用反编译工具找一个代码,以便去理解代码原理。XJad.exe
找到class文件,反编译会把class文件转成java文件。
在out文件里面找。
然后把这个class拖进去XJad反编译软件里面。
这样子就能看清楚了。
对比看一下:
字符串拼接,如果等号邮编是字符串字面值拼接,不会产生新对象。