仍然与js Prototype混淆

Still confused with js Prototype

本文关键字:Prototype 混淆 js      更新时间:2023-09-26

我对原型的实际功能感到困惑。我现在正在学习HTML画布,对于其中一个示例,它使用原型来声明draw方法。但是,使用原型和简单地将其放入构造函数本身有什么区别呢?

这不是书中的例子吗:

function Ball (radius, color) {
    if (radius === undefined) { radius = 40; }
    if (color === undefined) { color = "#ff0000"; }
    this.x = 0;
    this.y = 0;
    this.radius = radius;
    this.rotation = 0;
    this.scaleX = 1;
    this.scaleY = 1;
    this.color = utils.parseColor(color);
    this.lineWidth = 1;
    }

Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
//x, y, radius, start_angle, end_angle, anti-clockwise
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};

与放入此相同?:

function Ball(radius, color){
...
this.draw = function (context) {
    context.save();
    context.translate(this.x, this.y);
    context.rotate(this.rotation);
    context.scale(this.scaleX, this.scaleY);
    context.lineWidth = this.lineWidth;
    context.fillStyle = this.color;
    context.beginPath();
    //x, y, radius, start_angle, end_angle, anti-clockwise
    context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
    context.closePath();
    context.fill();
    if (this.lineWidth > 0) {
    context.stroke();
    }
    context.restore();
    };
}

prototype是一个由所有其他对象共享的对象,这些对象将其作为prototype,这导致动态添加到prototype的方法可以由所有实例共享。

function ClassA(){
    this.sayHello = function(){
        return "hello!";
    }
}
var instanceA = new ClassA();
instanceA.sayHello();//return "hello!";
//add a method to instanceA
instanceA.sayBye = function(){ return "Bye!"; }
var instanceB = new ClassA();
instanceB.sayBye(); //error, sayBye is not a method of instanceB.
//But, this really works
ClassA.prototype.sayBye = function(){ return "Bye!"; }

而且,由于所有实例共享一个prototype,因此所有方法都只停留在内存中的一个位置。在第二个实现中,每个实例都有自己的方法,这会导致使用大量内存。

将方法排除在类的定义之外可以使代码更加干净和可读,尽管这并不是有力的证据。

有了原型,开发人员更容易用OOP风格编写代码。

 function ClassB(){
 }
 ClassB.prototype = new ClassA();
 // The equivalent approach may be this
 function ClassB(){
     ClassA.apply(this);
 }

这两种方法都可以做同样的工作,所以选择你喜欢的任何一种。

没有太大区别。主要区别在于,通过原型创建的方法不能访问对象的私有成员。

function Ball (radius, color) {
    if (radius === undefined) { radius = 40; }
    if (color === undefined) { color = "#ff0000"; }
    this.x = 0;
    this.y = 0;
    this.radius = radius;
    this.rotation = 0;
    this.scaleX = 1;
    this.scaleY = 1;
    this.color = utils.parseColor(color);
    this.lineWidth = 1;
    var privateVar = 0;
    function privateFunction() {
        // anything
    }
}
Ball.prototype.draw = function() {
   privateFunction(); // doesn't work.
   privateVar = 2; // doesn't work
   this.lineWidth = 2; // this will work.
};