首先是augment的
YUI().use('attribute', function(Y) {
function MyClass(cfg) {
var attrs = {
"foo" : {
value : 5,
writeOnce :true
},
"bar" : {
value : "Hello World!"
},
"foobar" : {
value : true
}
};
this.addAttrs(attrs, cfg);
}
Y.augment(MyClass, Y.Attribute);
function display(o, title) {
var str = title + "/ foo: " + o.get("foo") + "/ bar: " + o.get("bar") + "/ foobar: " + o.get("foobar");
Y.log(str);
}
var my1 = new MyClass();
display(my1, "my1"); //my1/ foo: 5/ bar: Hello World!/ foobar: true
my1.set("foo", 10);
my1.set("bar", "Fake World!");
my1.set("foobar", false);
display(my1, "my1"); //my1/ foo: 5/ bar: Fake World!/ foobar: false
var my2 = new MyClass({
foo : 15,
bar : "Young World!",
foobar : true
});
display(my2, "my2"); //my2/ foo: 15/ bar: Young World!/ foobar: true
var my3 = new MyClass({
"foo" : 15,
"bar" : "Young World!",
"foobar" : true
});
display(my3, "my3"); //my2/ foo: 15/ bar: Young World!/ foobar: true
});
其次是extend的
YUI().use('attribute', function(Y) {
function MyClass(cfg) {
MyClass.superclass.constructor.call(this, name);
var attrs = {
"foo" : {
value : 5
},
"bar" : {
value : "Hello World!"
},
"foobar" : {
value : true
}
};
this.addAttrs(attrs, cfg);
}
Y.extend(MyClass, Y.Attribute);
function display(o, title) {
var str = title + "/ foo: " + o.get("foo") + "/ bar: " + o.get("bar") + "/ foobar: " + o.get("foobar");
Y.log(str);
}
var my1 = new MyClass();
display(my1, "my1"); //my1/ foo: 5/ bar: Hello World!/ foobar: true
my1.set("foo", 10);
my1.set("bar", "Fake World!");
my1.set("foobar", false);
display(my1, "my1"); //my1/ foo: 10/ bar: Fake World!/ foobar: false
var my2 = new MyClass({
foo : 15,
bar : "Young World!",
foobar : true
});
display(my2, "my2"); //my2/ foo: 15/ bar: Young World!/ foobar: true
var my3 = new MyClass({
"foo" : 15,
"bar" : "Young World!",
"foobar" : true
});
display(my3, "my3"); //my2/ foo: 15/ bar: Young World!/ foobar: true
});
发现区别没有~~~
extend由于是继承,所以必须要在子类的构造方法中将参数用其父类的构造函数调用
注意my2与my3,说明,传参时是否使用字符串的形式都不影响
extend的简单示例:
YUI().use('node', function(Y) {
function Bird(name) {
this.name = name;
}
Bird.prototype.flighted = true; // Default for all Birds
Bird.prototype.isFlighted = function () { return this.flighted };
Bird.prototype.getName = function () { return this.name };
function Chicken(name) {
// Chain the constructors
Chicken.superclass.constructor.call(this, name);
}
// Chickens are birds
Y.extend(Chicken, Bird);
// Define the Chicken prototype methods/members
Chicken.prototype.flighted = false; // Override default for all Chickens
var chick = new Chicken("sss");
var chick1 = new Chicken("aa");
var ma = new Bird("dsds");
Y.log(chick.getName() + ": " + chick.isFlighted()); // sss: false
Y.log(chick1.getName() + ": " + chick1.isFlighted()); // aa: false
Y.log(ma.getName() + ": " + ma.isFlighted()); // dsds: true
Y.log(chick instanceof Bird? "1" :"2"); // 1
});