在 OOP 方面,我有点理解 Javascript 和 Java 之间的区别。我读了我手头的 Javascript 书的最后一段,但我不完全理解它的意思,你能进一步解释并提供例子来说明两种语言之间的区别吗?
“在许多面向对象的编程语言中,可以定义一个对象类,然后创建作为该类实例的单个对象。”
谢谢!
最佳答案
大多数人所做的是使用构造函数,如下所示:
function MyClass(a, b) {
// Private instance properties
var x = "secret";
var y = "also secret";
// Public instance properties
this.a = a;
this.b = b;
// "Privileged" methods; can access private and public properties
this.foo = function () {
return x + " " + this.a;
};
}
// "Public" methods; cannot access private properties
MyClass.prototype.bar = function () {
return this.a + " " + this.b;
};
// Public shared properties; not recommended:
MyClass.prototype.w = "stuff";
// Static methods
MyClass.baz = function () {
return "i am useless";
};
然后你可以像这样使用这个构造函数:
var instance = new MyClass("hi", "Meen");
asssert.equal(instance.foo(), "secret hi");
assert.equal(instance.bar(), "hi Meen");
assert.equal(MyClass.baz(), "i am useless");
var also = new MyClass("hi", "Raynos");
instance.w = "more stuff";
assert.equal(also.w, "more stuff");
如果你想做继承,你会做这样的事情:
function Inherited(a) {
// apply parent constructor function
MyClass.call(this, a, "Domenic");
}
Inherited.prototype = Object.create(MyClass.prototype);
var inherited = new Inherited("hello there good chap");
assert.equal(inherited.a, "hello there good chap");
assert.equal(inherited.foo(), "secret hello there good chap");
assert.equal(inherited.bar(), "hello there good chap Domenic");
关于javascript - OOP Javascript 与 Java(或其他语言,例如 PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8025093/