[英]How to do encapsulation in javascript
can you please tell me how to do encapsulation in javascript .I have a class Name Car .I want to extend this class with B class .Secondly I want to override and overload the methods in java script. 您能告诉我如何在javascript中进行封装吗?我有一个Name Car类。我想用B类扩展该类。其次,我想覆盖并重载Java脚本中的方法。
Here is my fiddle http://jsfiddle.net/naveennsit/fJGrA/ 这是我的小提琴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();
can you explain these two lines 你能解释这两行吗
Ferrari.prototype = new Car(); Ferrari.prototype = new Car(); This line show Ferrari is extend by car ? 这条线显示法拉利是开车吗?
Ferrari.prototype.constructor = Ferrari;
what is the used of this line ? 这条线有什么用?
JS, by design does not provide a built-in way to manage the visibility of members of an object. JS,根据设计,没有提供内置的方法来管理对象成员的可见性。 but its flexible enough to allow us to do encapsulation. 但其灵活性足以允许我们进行封装。
Effective write up i found for you is http://www.codeproject.com/Articles/108786/Encapsulation-in-JavaScript 我为您找到的有效文章是http://www.codeproject.com/Articles/108786/Encapsulation-in-JavaScript
Ferrari.prototype = new Car()
This method adds Car poperties to the Ferrari's prototype. 这种方法使法拉利的原型车增加了汽车性能。 Whatever is returned by the Car(), is added to the existing Ferrari's prototype. Car()返回的所有内容都会添加到现有的法拉利原型中。
Ferrari.prototype.constructor = Ferrari
Prototype has a constructor property which is overriden by this call Ferrari.prototype = new Car() . 原型具有构造函数属性,此调用将覆盖此属性Ferrari.prototype = new Car() 。 This is manually resetting it again. 这是手动重新设置。
prototype and constructor object properties 原型和构造函数对象属性
I have edited your fiddle. 我已经编辑了你的小提琴。 http://jsfiddle.net/fJGrA/3/ http://jsfiddle.net/fJGrA/3/
Using closure in javascript you can hide elements within an object or function. 在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.
Whenever a variable is created with a var keyword within a function, it is accessible only in the scope of that function. 只要在函数内使用var关键字创建变量,就只能在该函数的范围内对其进行访问。 Effectively, being private to it. 实际上,对其保密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.