要创建 Point 的新实例,必须使用 new 操作符。以这种方式调用构造函数实际上会经历以下 4
个步骤:
(1) 创建一个新对象;
(2) 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象) ;
(3) 执行构造函数中的代码(为这个新对象添加属性) ;
(4) 返回新对象。
老语法
function Point (x,y) {
// console.log('Point init~~~');
this.x = x;
this.y = y;
}
// var a = new Point(4,5); #实例化必须带new
// console.log(a)
function Point123(x,y,z){
// console.log('Point123 init~~~')
Point.call(this,x,y); //借助call注入this
this.z = z
}
// console.log(Point123)
var b = new Point123(10,11,12)
console.log(b)
新语法
继承
class Point{
constructor(x,y){
console.log('Point init~~~')
this.x = x
this.y = y
this.show = () => console.log(this.x, this.y)
}
show () {
console.log(this.x, this.y);
// return this.x,this.y;
}
}
// let p1 = new Point(1,2);
// console.log(p1)
class Point123 extends Point{
constructor(x,y,z){
super(x,y);
this.z = z
this.show = () => console.log(this.x,this.y,this.z)
console.log('Point123~~~')
}
show (x){
// super.show()
console.log(super.show(),this.z)
}
}
let p2 = new Point123(10,11,12);
console.log(p2)
p2.show()
静态方法
class Point{
constructor(x,y){
console.log('Point init~~~')
this.x = x
this.y = y
// this.show = () => console.log(this.x, this.y)
}
//静态的,就是类的
static show (x,y) { // 等效为Python中的classmethod
// console.log(this.x, this.y); ;类方法就不能用实例调用了
console.log(x,y) //可以这样调用
console.log(typeof this,'~~~~~~~~~')
// return this.x,this.y;
}
}
let p1 = new Point(1,2);
console.log(p1)
//p1.show() 不能用实例调用
Point.show(3,4)
p1.constructor.show(5,6) //这样可以
解决this问题
var obj = {
name:100,
getName:function () {
console.log(this.name,'in obj+++++')
return function (x, y) { //改成箭头函数就没this的问题了,但是老版本有可能没用箭头函数
// console.log(this)
console.log(this.name,x,y) //这个this是全局跟obj实例没关系
}
}
}
anormalfunc = obj.getName()
// anormalfunc.call(obj,...[1,2]) //把obj给this
// anormalfunc.apply(obj,[3,33])
anormalfunc.bind(obj)
console.log(anormalfunc.bind(obj))
obj.getName().bind(obj)(1,3)
改成箭头函数可以直接调用obj,getName()