我已经做了很多尝试来理解JavaScript中的OOP都没有成功.
到目前为止,我读过的所有文章都非常混乱,并且没有用JS简洁地解释OOP.
作为理解JavaScript中的OOP的最后尝试,请问有人可以将以下代码转换为JS吗?
public class Base
{
public String firstName; // public scope to simplify
public String lastName; // the same as above
Base(String firstName, String lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
}
public class Derived extends Base
{
public int age; // public scope to simplify
Derived(String firstName, String lastName, int age)
{
super(firstName, lastName);
this.age=age;
}
}
内部main()
Derived person = new Derived("John", "Doe", 25);
System.out.println("My name is " + person.firstName + " " + person.lastName + " and I have " + person.age + " years old.");
输出:
My name is John Doe and I have 25 years old.
您可以将其转换为JavaScript吗?
另一个问题:我们可以在JavaScript中使用多态性吗?
解决方法:
由于JavaScript是基于原型的,因此没有Class之类的东西.您可以使用构造函数(函数)来创建自定义数据类型并提供原型继承.
function Base (firstName, lastName) {
// same as public in Java
this.firstName = firstName;
this.lastName = lastName;
}
function Derived (firstName, lastName, age) {
// same as calling super class in Java, and you should explicitly bind this
Base.apply(this, arguments);
this.age = age;
}
// same as extends in Java, you just override Derived.prototype with super class prototype and you should explicitly set constructor if you want later check instanceof.
Derived.prototype = Object.create(Base.prototype, {
// if you omit this line than instanceof Derived would be false, since instanceof check by prototype chain constructors.
constructor: {
value: Derived
}
});
var person = new Derived("John", "Doe", 25);
console.log(person instanceof Derived); // true
console.log(person instanceof Base); // true
console.log("My name is " + person.firstName + " " + person.lastName + " and I have " + person.age + " years old.");
关于多态,如果您问的是方法重载,那么就没有这种事情了,但是,由于javascript是弱类型的动态语言,因此您可以通过检查该参数的arguments长度和typeof来获得相同的结果.我相信多态的其他概念与Java中的工作原理相同.
简单例如:
function bar(a, b) {
if (arguments.length === 2) {
var isInts = [].every.call(arguments, function(val) {
return !isNaN(val);
});
if (isInts) {
console.log(a + b);
}
} else if (arguments.length > 2) {
console.log([].join.call(arguments, ""));
}
}
bar(2, 5);
bar("Hello", ", ", "world", "!");
标签:oop,javascript
来源: https://codeday.me/bug/20191030/1964098.html