2

你能告诉我如何在javascript中进行封装。我有一个类名称汽车。我想用B类扩展这个类。其次我想覆盖和重载java脚本中的方法。

这是我的小提琴 http://jsfiddle.net/naveennsit/fJGrA/

   //Define the Car class
function Car() { }
Car.prototype.speed= 'Car Speed';
Car.prototype.setSpeed = function(speed) {
    this.speed = speed;
    alert("Car speed changed");
}


//Define the Ferrari class
function Ferrari() { }
Ferrari.prototype = new Car();


// correct the constructor pointer because it points to Car
Ferrari.prototype.constructor = Ferrari;

// replace the setSpeed method
Ferrari.prototype.setSpeed = function(speed) {
    this.speed = speed;
    alert("Ferrari speed changed");
}

var car = new Ferrari();
car.setSpeed();

你能解释一下这两行吗

Ferrari.prototype = new Car(); 这条线显示法拉利是坐车延伸的?

 Ferrari.prototype.constructor = Ferrari;

这条线有什么用?

4

2 回答 2

0
Ferrari.prototype = new Car()

这种方法将汽车属性添加到法拉利的原型中。Car() 返回的任何内容都将添加到现有的法拉利原型中。

Ferrari.prototype.constructor = Ferrari

Prototype 有一个构造函数属性,该属性被此调用Ferrari.prototype = new Car()覆盖。这是再次手动重置它。

原型和构造函数对象属性

我已经编辑了你的小提琴。http://jsfiddle.net/fJGrA/3/

在 javascript 中使用闭包可以隐藏对象或函数中的元素。

function foo(args){
//this is a private variable.
 var _name = ""

 return{
  getname:function(){
   return _name
   }
  }

 }

 bar = new foo()

 // name can only be accessed from inside the foo function.

每当在函数中使用var关键字创建变量时,它只能在该函数的范围内访问。实际上,是私有的。

于 2013-09-16T08:56:15.133 回答
0

JS 在设计上没有提供内置的方法来管理对象成员的可见性。但它足够灵活,可以让我们进行封装。

我为您找到的有效文章是http://www.codeproject.com/Articles/108786/Encapsulation-in-JavaScript

于 2013-09-16T08:52:59.713 回答