gpt4 book ai didi

javascript - 如何在javascript中进行封装

转载 作者:行者123 更新时间:2023-11-30 06:29:23 25 4
gpt4 key购买 nike

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

这是我的 fiddle 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;

这条线有什么用?

最佳答案

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

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

关于javascript - 如何在javascript中进行封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18823897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com