我有点理解JOP和Java在OOP方面的区别.我阅读了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";
};
Run Code Online (Sandbox Code Playgroud)
然后,您将使用此构造函数,如下所示:
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");
Run Code Online (Sandbox Code Playgroud)
如果你想继承,你会做类似的事情:
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");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2710 次 |
最近记录: |