`
DavyJones2010
  • 浏览: 154288 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Javascript: Object Model & Define Object Using Factory Method

阅读更多

 1. One major difference between dynamic language and static language is that:

    Dynamic language can add attributes/methods for a predefined type.

    But static language can not realize this, or else we have to change the bean.

<html>
	<head>
		<script type="text/javascript">
		var object = new Object();
		object.name = "davy";

		for(var v in object){
		document.write(v + " = " + object[v] + "<br/>");
		document.write(v + " = " + object.name + "<br/>");
		}

		</script>
	</head>
</html>

   The result is "name = davy".

   Thess two different ways to represent the attributes.

   But the first one is a more dynamic approach.

 

2. There are two different ways to define attributes for an object.

    1. The first one is: <Just the same code as above>

<html>
	<head>
		<script type="text/javascript">
		var object = new Object();
		object.name = "davy";

		for(var v in object){
		document.write(v + " = " + object[v] + "<br/>");
		document.write(v + " = " + object.name + "<br/>");
		}

		</script>
	</head>
</html>

   2. The second one is: 

<html>
	<head>
		<script type="text/javascript">
		var object = new Object();
		object["name"] = "davy";

		for(var v in object){
		document.write(v + " = " + object[v] + "<br/>");
		document.write(v + " = " + object.name + "<br/>");
		}

		</script>
	</head>
</html>

 

3. We can even delete attributes from object.

    Use uniary operator 'delete'

<html>
	<head>
		<script type="text/javascript">
		var object = new Object();
		object.name = "davy";

		for(var v in object){
		document.write(v + " = " + object[v] + "<br/>");
		document.write(v + " = " + object.name + "<br/>");
		}

		delete object.name;

		for(var v in object){
		document.write(v);
		}

		</script>
	</head>
</html>

   

4. Create an object with customized attribtes & values.

<html>
	<head>
		<script type="text/javascript">
		var person = {name:"davy", gender:"male"};

		for(var a in person){
		document.write(a + " = " + person[a] + "<br/>");
		}

		</script>
	</head>
</html>

   Here we created an object called "person" which has properties named "name" and "gender".

   This is the most popular way we define a customized object.

   The only way we know what attributes an object has provided by third-party lib is refer to the api doc.

   This is quite different from that in java.

 

5. Array

    1.  There are two ways to define an array object as described before.

<html>
	<head>
		<script type="text/javascript">
		var array = new Array();
		array.push("1");
		array.push(3);

		alert(array.length);
		</script>
	</head>
</html>
<html>
	<head>
		<script type="text/javascript">
		var array = ["1", "3"];

		alert(array.length);
		</script>
	</head>
</html>

       The second approach is more frequently used cause it easier.

       The size of array in JS is automatically reallocated.

   2. There is a method named "sort" in array. By using it, we can sort the array(It directly sorts the datasource, not the copy).

<html>
	<head>
		<script type="text/javascript">
		var array = ["1", "3", "0", "-1", "2"];
		array.sort();
		document.write(array);
		</script>
	</head>
</html>

    The result is "-1, 0, 1, 2, 3". The elements are sorted as string.

<html>
	<head>
		<script type="text/javascript">
		var array = [1, 3, 0, -1, 2, 11, 21, 32, 9];
		array.sort();
		document.write(array);
		</script>
	</head>
</html>

   The result is "-1,0,1,11,2,21,3,32,9".  The elements are sorted as string.

   The reason is that in "sort" function,the "toString" method would be invoked for each element before comparing values.

   So we have to provide customized sorting strategy for array if we want a different one.

<html>
	<head>
		<script type="text/javascript">
		function compare(num1, num2){
			var temp1 = parseInt(num1);
			var temp2 = parseInt(num2);
			if(temp1 < temp2){
				return -1;
			}else if(temp1 == temp2){
				return 0;
			}else{
				return 1;
			}
		}
		var array = [1, 3, 0, -1, 2, 11, 21, 32, 9];
		array.sort(compare);
		document.write(array);
		</script>
	</head>
</html>

   This is quite the same with that in JAVA.

   The result is "-1, 0, 1, 2, 3, 9, 11, 21, 32".

   The function "compare" is actually a reference to an object as explained before.

   We can use anonymous inner function(Just the same representation as that in JAVA) to write the compare function.

<html>
	<head>
		<script type="text/javascript">
		var array = [1, 3, 0, -1, 2, 11, 21, 32, 9];
		array.sort(function (num1, num2){
			var temp1 = parseInt(num1);
			var temp2 = parseInt(num2);
			if(temp1 < temp2){
				return -1;
			}else if(temp1 == temp2){
				return 0;
			}else{
				return 1;
			}
		});
		document.write(array);
		</script>
	</head>
</html>

   This kind of representation is quite frequently used in JQuery.

<html>
	<head>
		<script type="text/javascript">
		var person = {name:"davy", gender:"male", 
			display:function(){
			document.write("name = " + this.name + ",gender = " + this.gender + "<br/>");
			}, 
			reverseDisplay:function(){
			document.write("gender = " + this.gender + ",name = " + this.name + "<br/>");
			}};
		person.display();
		person.reverseDisplay();
		</script>
	</head>
</html>

    The result is "name=davy, gender=male" and "gender=male, name=davy"

    So we can define the attribute as well as the operation.

 

6. Ways to define an object.

    1. Extend operations and attributes based on already instantiated object.

<html>
	<head>
		<script type="text/javascript">
		var person = {name:"davy", gender:"male"};
		person.score = "test";
		person.reverseDisplay = function (){
			document.write("gender = " + this.gender + ", name = " + this.name + ", score = " + this.score);
		}
		person.reverseDisplay();
		</script>
	</head>
</html>

   The defect is that if we want to create thousands of this kind of person object which has the attribute of name, gender and score, and has operation of reverseDisplay.

   It would be a lot of code copy.

   

   2.Use factory method.

<html>
	<head>
		<script type="text/javascript">
		function createPerson(){
			var person = {name:"davy", gender:"male"};
			person.score = "test";
			person.reverseDisplay = function (){
				document.write("gender = " + this.gender + ", name = " + this.name + ", score = " + this.score + "<br/>");
			}
			return person;
		}

		var p1 = createPerson();
		var p2 = createPerson();

		p1.name = "jones";
		p1.reverseDisplay();
		p2.reverseDisplay();

		p2.name = "calypso";
		p2.gender = "female";
		p1.reverseDisplay();
		p2.reverseDisplay();

		</script>
	</head>
</html>

    It turned out that the two persons are totally isolated objects. And one's change won't impact another.

    We can even pass params to create object that satisfy our needs.

<html>
	<head>
		<script type="text/javascript">
		function createPerson(name, gender){
			var person = {name:name, gender:gender};
			person.score = "100";
			person.reverseDisplay = function (){
				document.write("gender = " + this.gender + ", name = " + this.name + ", score = " + this.score + "<br/>");
			}
			return person;
		}

		var p1 = createPerson("davy", "male");
		var p2 = createPerson("calypso", "female");

		p1.reverseDisplay();
		p2.reverseDisplay();
		</script>
	</head>
</html>

   The result is "gender=male, name=male" and "gender=female, name=calypso".

   Still there are some defacts when using this kind of instination.

   When using java, the function defined in class are shared by all the objects.

   But when using this kind of instiantion, every object has its own function and don't share with other.

   That would be high cost.

<html>
	<head>
		<script type="text/javascript">
		var reverseDisplay = function (){
			document.write("gender = " + this.gender + ", name = " + this.name + ", score = " + this.score + "<br/>");
		};
		function createPerson(name, gender){
			var person = {name:name, gender:gender};
			person.score = "100";
			person.reverseDisplay = reverseDisplay;
			return person;
		};

		var p1 = createPerson("davy", "male");
		var p2 = createPerson("calypso", "female");

		p1.reverseDisplay();
		p2.reverseDisplay();
		</script>
	</head>
</html>

   This is an optimized solution.

   Good practice: Share methods.

 

   3. Using constructor.

<html>
	<head>
		<script type="text/javascript">
		var reverseDisplay = function (){
			document.write("gender = " + this.gender + ", name = " + this.name + ", score = " + this.score + "<br/>");
		};
		function Person(name, gender, score){
			// Before executing first line, js engine(browser) will create an inner object called "this"
			this.name = name;
			this.gender = gender;
			this.score = score;
			this.reverseDisplay = reverseDisplay;
			// After executing the last line, js engine(browser) will return the object called "this"
		};

		var p1 = new Person("davy", "male", "100");
		var p2 = new Person("calypso", "female", "99");

		p1.reverseDisplay();
		p2.reverseDisplay();
		</script>
	</head>
</html>

    4. Using prototype create object

        We have to discriminate "prototype" from that of a lib of js which is called "prototype".

        As there is an attribute called "prototype", so every object in js has the attribute called "prototype". 

<html>
	<head>
		<script type="text/javascript">
		function Person(){
		};
		
		Person.prototype.username = "davy";
		Person.prototype.password = "hello";

		Person.prototype.showPerson = function (){
			document.write(this.username + ", " + this.password + "<br/>");
		}

		var person1 = new Person();
		var person2 = new Person();

		person1.username = "jones";
		person1.showPerson();
		person2.showPerson();

		</script>
	</head>
</html>
    Still, there are some defects using this. 

    1) We cannot pass params into constructor to instantiate attributes.

        We have to modify the attribute only after we have instantiated the object.

    2) It is just conincidence that when we change one username, the other one is not affected.

        It just not the case when it comes into reference type/object type. 

<html>
	<head>
		<script type="text/javascript">
		function Person(){
		};
		
		Person.prototype.username = new Array();
		Person.prototype.username.push("aaa");
		Person.prototype.username.push("bbb");
		Person.prototype.password = "hello";

		Person.prototype.showPerson = function (){
			document.write(this.username + ", " + this.password + "<br/>");
		}

		var person1 = new Person();
		var person2 = new Person();

		person1.username.push("davy");
		person1.username.push("jones");
		person1.password = "world";

		person1.showPerson();
		person2.showPerson();
		</script>
	</head>
</html>
   The expected output is "davy,jones,world" and "aaa,bbb,hello". 

   The actual output is "aaa,bbb,davy,jones, world" and "aaa,bbb,davy,jones,hello".

   Q: Why? 

   A: We can think of "aaa" as static/const just like that in java.

       We should regard username as reference type.

       When we push data into username, we didn't change the pointer actually.

       When we change the password, we changed the pointer actually.


     Good To Know:

     When we are using prototype to generate object, all the object of this kind will share the attributes in prototype.

     The change of attribute by one object will impact all other objects. 

  • 大小: 42.1 KB
分享到:
评论

相关推荐

    The Principles of Object-Oriented JavaScript 1st Edition

    If you've used a more traditional object-oriented language, such as C++ or Java, JavaScript probably doesn't seem object-oriented at all. It has no concept of classes, and you don't even need to ...

    FukoSwizzle:在cxx中使用swizzle

    #define SWIZZLE_BASE_TYPE float #include "swizzle_types" #undef SWIZZLE_BASE_TYPE int main() { float2 a(1, 2); float3 b(1, 2, 3); float4 c(1, 2, 3, 4); a = b.zy; b.rg = b.rb; c.wzy = b; std::...

    通过C++来实现类似JAVA和C#的反射原理例子程序

    此外,还可以考虑使用第三方库,如`Boost.TypeIndex`或`MetaObject`,它们提供了更完善的反射功能。 在C++中实现反射虽然相对复杂,但通过这种方法,我们可以创建更灵活、可扩展的系统,尤其是在处理动态配置、序列...

    Mastering JavaScript Object-Oriented Programming

    Mastering JavaScript Object-Oriented Programming 2016 | ISBN: 1785889109 | English | 287 pages | PDF | 1.9 MB With this book, we'll provide you with a comprehensive overview of OOP principles in ...

    微信公众号平台与电影类网站对接源码

    说明几点:第九行:define(&quot;TOKEN&quot;, &quot;weixin&quot;);//token需要与微信后台保持一致。 第102行开始,数据库地址,数据库用户名,密码等都是自己服务器的数据库 播放页面及图片地址都是根据自己网站...

    Ruby Meta Programming: define_method or class_eval

    `define_method`和`class_eval`是Ruby元编程中的两个关键方法,它们被广泛用于动态地添加方法到类或者模块中。这篇文章将深入探讨这两个方法的用法和区别。 `define_method`方法允许我们传递一个符号和一个代码块来...

    Understanding Ruby's Object Model

    **Ruby对象模型详解** Ruby是一种面向对象的编程语言,其对象模型是其核心特性之一,它使得Ruby在处理...阅读`Understanding_Ruby_s_Object_Model.ppt`,你将获得更详细的解释和示例,进一步提升你的Ruby编程技能。

    aeduino dht11库文件

    dht11库文件 // // FILE: dht.h // VERSION: 0.1.01 // PURPOSE: DHT Temperature & Humidity Sensor library for Arduino // ... // // HISTORY: ... #define DHT_LIB_VERSION "0.1.01

    object_envi_resize__define_IDl_

    标题中的"object_envi_resize__define_IDl_"很可能是指一个使用IDL(Interactive Data Language)编写的ENVI(Environment for Visualizing Images)扩展程序,该程序专注于图像对象的重采样操作。ENVI是一款广泛...

    spark-md5.js

    可用于大文件的哈希 ... define(factory); } else { // Browser globals (with support for web workers) var glob; try { glob = window; } catch (e) { glob = self; } glob.SparkMD5 = factory(); } }

    ICC8051 Micro Series 8051 C-Compiler V4.10A/DOS

    -o file Put object on: &lt;file&gt; -Oprefix Put object on: &lt;prefix&gt; &lt;source&gt; -b Make object a library module -P Generate PROMable code -g{OA} Enable global typecheck O: Disable object code type-info A...

    graphql-guard:GraphQL的简单授权gem

    # Define a type class PostType &lt; GraphQL :: Schema :: Object field :id , ID , null : false field :title , String , null : true end # Define a query class QueryType &lt; GraphQL :: Schema :: ...

    c++操作Excel操作的DLL

    对于C++操作Excel,最常用的库是Microsoft的COM(Component Object Model)接口,如Microsoft Office Automation或Open XML SDK。这些接口允许开发者使用C++调用Excel对象模型,从而进行读写操作。例如,可以使用`...

    axy-define-asm:装配 axy.define 项目

    装配 axy.define 项目 见 。 安装 npm install axy-define-asm 命令行实用程序 axy-define-asm 。 位于目录bin 。 例子: axy-define-asm --source=js --outDir=outJS 没有参数,只有选项: --addExt=ext Add ...

    基于内容的垃圾邮件过滤

    #define MAX(a,b) (a&gt;=b)?a:b; #define MIN(a,b) (a)?a:b; using namespace std; using namespace boost::filesystem; using namespace boost; spamtrain::spamtrain(){ totalfiles = 0; spamfiles = 0 ; ...

    dynamix:C ++中多态性的新观点

    该库使用dynamix::object类型作为占位符,可以使用现有的类(mixins)扩展其实例,从而为特定实例提供所有这些类型的功能。 访问新形成的类型的接口是通过消息完成的,消息是库生成的独立函数,可以将其视为方法。 ...

    cpp-httplib:仅C ++标头的HTTPHTTPS服务器和客户端库

    简单的例子服务器# define CPPHTTPLIB_OPENSSL_SUPPORT# include " path/to/httplib.h "// HTTPhttplib::Server svr;// HTTPShttplib::SSLServer svr;svr.Get( " /hi " , []( const httplib::Request &, httplib::...

Global site tag (gtag.js) - Google Analytics