高洛峰2017-04-10 15:01:54
这里的this是指向circle的实例的,call的作用是改变原有方法中的上下文,即this的指向,拿具体例子来说
var createjs = {};
createjs.Shape = function () {
this.name = 'shape';
}
function Cirle(){
createjs.Shape.call(this);
}
var circle=new Cirle();
conosle.log(circle.name);
控制台就会打印出shape,只需要理解下call的用法就可以了
var createjs = {};
createjs.Shape = function () {
this.name = 'shape';
}
function Cirle() {
createjs.Shape.call(this);
this.setCircleType = function (type) {
this.circleTye = type;
}
}
var circle = new Cirle();
circle.setCircleType(2);
console.log(circle.circleTye);
每次执行了setCircleType方法,当前的实例就会记录下circleType,也就是说,通过实例的circleType属性,可以知道当前的circleType是什么。
这里是利用JavaScript的原型链实现类的继承,具体内容题主请自行询问度娘,网上教程很多。
继承的功能想必我不用多说了吧,看个例子
var createjs = {};
createjs.Shape = function () {
this.name = 'shape';
}
function Cirle() {
}
Cirle.prototype=new createjs.Shape();
var circle = new Cirle();
console.log(circle);
Cirle方法什么没干,但是打印出的实例却有name属性,其实就是通过Cirle.prototype=new createjs.Shape()实现的继承。
hope help you。说的不对的还请包含指正!
迷茫2017-04-10 15:01:54
这就是古老的JS对象继承的写法,我给你改成ES6的写法,你就能明白了。
javascript
"use strict"; class Circle extends createjs.Shape{ // 构造函数 constructor(){ super(); this.setCircleType(Circle.TYPE_RED); } // setCircleType方法 setCircleType(type){ switch(type){ case Circle.TYPE_RED: this.setColor("#ff0000"); break; case Circle.TYPE_GREEN: this.setColor("#00ff00"); break; } } // setColor方法 setColor(color){ this.graphics.beginFill(color); this.graphics.drawCircle(0,0,50); this.graphics.endFill(); } }
这就是Circle类继承createjs.Shape的ES6写法,和你上面那些代码是相同语义的(需要在较新的浏览器才支持)
javascript
Circle.Type_RED=1; Circle.Type_GREEN=2;
这两行照些,和Circle类无关,只是个模仿枚举的用法。