面向物件風格與物件關聯風格
阿新 • • 發佈:2018-12-12
對相關聯:
Foo={ init:function(name){ this.name=name; }, sayName:function(){ return 'I am '+this.name; } }; Bar=Object.create(Foo); //* Bar.greet=function(){ return 'Hello, '+this.sayName()+'.'; } var b1=Object.create(Bar); b1.init('Tom'); //* var b2=Object.create(Bar); b2.init('Mary'); //* b1.greet(); //"Hello, I am Tom." b2.greet(); //"Hello, I am Mary."
面向物件:
function Foo(name){ this.me=name; } Foo.prototype.sayName=function(){ return 'I am '+this.me; } function Bar(name){ Foo.call(this,name); //* } Bar.prototype=Object.create(Foo.prototype); Bar.prototype.greet=function(){ return 'Hello, '+this.sayName()+'.'; } var b1=new Bar('tom'); //* var b2=new Bar('mary'); //* b1.greet(); //"Hello, I am tom." b2.greet(); //"Hello, I am mary." b1.sayName(); //"I am tom."