javascript object oriented 面向对象编程初步

2019-06-03 10:23:09王冬梅


The following is an example of inheritance through functions.

下面一个例子演示了如何继承通过function . 
<script language="javascript" type="text/javascript"> 
<!-- 

// thanks to webreference 

function superClass() { 
this.supertest = superTest; //attach method superTest 


function subClass() { 
this.inheritFrom = superClass; 
this.inheritFrom(); 
this.subtest = subTest; //attach method subTest 


function superTest() { 
return "superTest"; 


function subTest() { 
return "subTest"; 



var newClass = new subClass(); 

alert(newClass.subtest()); // yields "subTest" 
alert(newClass.supertest()); // yields "superTest" 

//--> 
</script>
基于继承的原型是遥远的.为 javascript 应用程序在许多场合.
(基于原型的继承在许多javascript的应用场合是非常有用的.)

对象作为联合数组
正如你所知, (.)操作符能够用来存储.[] 操作符用来操作数组.
<script language="javascript" type="text/javascript">
<!--

// These are the same
object.property
object["property"]

//-->
</script>

<SCRIPT LANGUAGE="javascript">
<!--
function Circle (xPoint, yPoint, radius) {
this.x = xPoint; 
this.y = yPoint; 
this.r = radius; 
}

var aCircle = new Circle(5, 11, 99);
alert(aCircle.x);
alert(aCircle["x"]);
//-->
</SCRIPT>
How do I loop through properties in an object?
You need to use a for/in loop.
我们可以通过for in循环来遍历对象的属性。

<script language="javascript" type="text/javascript">
<!--

var testObj = {
prop1 : "hello",
prop2 : "hello2",
prop3 : new Array("hello",1,2)
}
for(x in testObj) alert( x + "-" + testObj[ x ] )
//-->
</script>
<SCRIPT LANGUAGE="javascript">
<!--
var Circle = { x : 0, y : 1, radius: 2 } // another example

for(p in Circle) 
alert( p + "-" + Circle[ p ] )
//-->
</SCRIPT>


The important thing to notice is that in the object syntax the property is an identifier, whereas in the array syntax, it's a string. The obvious benefits of using an array syntax to access an object is because of the literal data type, you can easily concat strings and play around with them to access an object. For this to work with the standard syntax, an eval() would need to be used.