zoukankan      html  css  js  c++  java
  • Javascript 面向对象实践

    踩到了坑,才能学到东西。

    记录我在慢慢的转向模块化遇到的问题以及解决的思路。

    1.采用立即执行函数,闭包的方式创建模块

    html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Module</title>
    	<script type="text/javascript" src="store.js"></script>
    	<script type="text/javascript">
    		var store = storeModule.getStore({x:1});	
    	</script>
    </head>
    <body>
    	
    </body>
    </html>
    

    js:

     
    var storeModule = (function(){
    	var Store = function(opinion){
    		this.opinion = opinion;
    	}
    
    	Store.prototype = {
    		constructor:Store,
    		init:function(opinion){
    			console.log('a:',opinion);
    			this.opinion = opinion;
    			console.log('b:',this.opinion);
    		}
    	}
    
    	return {
    		getStore:function(opinion){
    			var storeInstance = Object.create( Store.prototype );
    			Store.prototype.init.apply(storeInstance,arguments);
    			
    			// var storeInstance2 = new Store(opinion);
    			// storeInstance2.init(opinion);
    			console.log('store end');
    			return storeInstance;
    		}
    	}
    	
    })();
    	
    
    

    坑:
    采用 Object.create( Store.prototype ) 这种方式创建对象,无法将参数opinion传递给Store这个function对象,百思不得其解,后来,参阅了一下Jquery的插件的源码,发现需要在 init:function(opinion)中增加一行this.opinion = opinion,否则传递不过去。

  • 相关阅读:
    237. 删除链表中的节点
    牛客网-第一场-J-Fraction Comparision
    1. 两数之和
    CCF-201903-1大中小
    学习Python
    Convert Sorted Array to Binary Search Tree
    3-1
    Merge Sorted Array
    Climbing Stairs
    Add Binary
  • 原文地址:https://www.cnblogs.com/ae6623/p/5404048.html
Copyright © 2011-2022 走看看