JavaScript高级<3>

来源:互联网 发布:房源中介系统源码 编辑:程序博客网 时间:2024/04/29 02:42

JavaScript  自定义对象

创建对象方式:方式一,对象初始化器方式;

方式二,构造函数方式;

<script type="text/javascript">var cc = {name : "cc",age : 22,shout : function() {alert("我是:" + this.name + "今年" + this.age + "岁了!");},action : function() {alert("会吃");}};alert(cc.name);alert(cc.age);cc.shout();cc.action();function Dog(name, age) {this.name = name;this.age = age;this.shout = function() {alert("我是:" + this.name + "今年" + this.age + "岁了!");};this.action = function() {alert("eat");};}var jack = new Dog("jack", 1);alert(jack.name);alert(jack.age);jack.shout();jack.action();</script>

对象属性定义:私有属性;对象属性;类属性

<script type="text/javascript">function C(){this.Object="对象属性";C.prototype.Object2="对象属性2";var privatePro="私有属性";}C.classPro="类属性";alert(C.classPro);var c=new C();alert(c.Object);alert(c.Object2);</script>

对象方法定义:私有方法;对象方法;类方法;

<script type="text/javascript">function C() {var privateFunc = function() {alert("私有方法");};privateFunc();this.objFunc = function() {alert("对象方法");};C.prototype.objFunc2 = function() {alert("对象方法2");};}C.classFunc = function() {alert("类方法");};C.classFunc();var c = new C();c.objFunc();c.objFunc2();</script>

JavaScript 实现封装性;上面例子便是。


JavaScript实现继承性;

Apply()实现属性和方法的继承;

Prototype实现原型的继承;


<script type="text/javascript">function Animal(name,age){this.name=name;this.age=age;this.shout=function(){alert("大家好!");};}function Dog(name,age){Animal.apply(this, [name,age]);}var jack=new Dog("jack",1);alert(jack.name);alert(jack.age);jack.shout();</script>

Dog.prototype=new Animal();

JavaScript实现多态特征;

<script type="text/javascript">function Animal() {this.shout = function() {alert("动物!");};}function Dog() {this.shout = function() {alert("狗");};}Dog.prototype = new Animal();function Cat() {this.shout = function() {alert("猫");};}Cat.prototype = new Animal();function shout(animal){if(animal instanceof Animal){animal.shout();}}var dog=new Dog();var cat=new Cat();shout(dog);shout(cat);</script>


0 0