首页 > 代码库 > 行为委托,简洁的 对象关联 编码风格

行为委托,简洁的 对象关联 编码风格

//来自http://www.qdfuns.com/notes/31180/55aa17cafe6e64eed5fba661cc018570.html
    //父类
        function Foo(who) {
            this.me = who;
        }
        Foo.prototype.identify = function() {
            return "I am: " + this.me;
        }
        function Bar(who) {
            //继承父类的属性
            Foo.call(this,who);
        }
        //继承父类的方法
        Bar.prototype = Object.create(Foo.prototype);
        Bar.prototype.speak = function() {
            alert(‘hello,‘ + this.identify() + ".");
        }
        
        //实例化Bar
        var b1 = new Bar("b1");
        var b2 = new Bar("b2");
        b1.speak();//"hello,I am: b1."
        b2.speak();//"hello,I am: b2."
    Foo = {
            init: function(who) {
                this.me = who;
            },
            identify: function() {
                return "I am" + this.me;
            }
        };
        Bar = Object.create(Foo);
        Bar.speak = function() {
            console.log("Hello, I am: " + this.identify() + ".");
        }
        var b1 = Object.create(Bar);
        b1.init("b1");
        var b2 = Object.create(Bar);
        b2.init("b2");
        
        b1.speak();
        b2.speak();
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Document</title>
	<style type="text/css">

	</style>
</head>
<body>
	<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.js"></script>
	<script type="text/javascript">
		//父类
		function Widget(width, height) {
			this.width = width || 50;
			this.height = height || 50;
			this.$elem = null;
		}
		
		Widget.prototype.render = function($where) {
			if(this.$elem) {
				this.$elem.css({
					width: this.width + "px",
					height: this.height + "px"
				}).appendTo($where);
			}
		}
		
		//子类
		function Button(width, height, label) {
			//调用super 构造函数
			Widget.call(this, width, height);
			this.label = label || "Default";
			
			this.$elem = $("<button>").text(this.label);
		}
		
		//让Button 继承 Widget
		Button.prototype = Object.create( Widget.prototype);
		
		//重写 render()
		Button.prototype.render = function($where) {
			//"super" 调用
			Widget.prototype.render.call(this, $where);
			this.$elem.click( this.onClick.bind(this));
		}
		
	 	Button.prototype.onClick = function(evt) {
	 		console.log("Button: " + this.label + "被点击了");
	 		alert("Button: " + this.label + "被点击了");
	 	}
	 	
	 	$(function() {
	 		var $body = $(document.body);
	 		var btn1 = new Button(123, 30, "hello");
	 		var btn2 = new Button(150, 40, "World");
	 		
	 		btn1.render($body);
	 		btn2.render($body);
	 	})
	</script>
</body>
</html>

  

行为委托,简洁的 对象关联 编码风格