zoukankan      html  css  js  c++  java
  • 简单学习JavaScript面向对象编程

    JavaScript是一种弱类型语言。有一种原型机制。

    1、创建一个空对象:var bill = {};

    给这个对象添加属性和方法:

      bill.name = "Bill E Goat";

      bill.sound = function() {

      console.log( 'bahhh!' );

      };

    调用对象的属性和方法:

    alert(bill.name);

    bill.sound();

    2、一般情况我们都不这样创建对象的,通常都是创建对象的同时,给他添加属性和方法。(接下来我们以这种情况作为例子)

    如:

    var bill = {

      name: "Bill E Goat",

      sound: function() {

      console.log( 'bahhh!' );

      }

     };

    调用方式也是一样:

    alert(bill.name);

    bill.sound();

    这样调用的方式阅读起来直观明了,不容易混淆。

    3、重写一下当前的sound方法,并添加一个参数。

    bill.sound = function(noise) {

      console.log(noise);

      };

    调用带参数的sound方法:bill.sound("带参数");

    而此时不带参数的sound方法就不能调用了。它已经被重写(覆盖)了。

    javascript不支持函数的重载,不像java那样,javascript支持可变参数个数。js不支持重载,但是他也不会报错。

    4、给该对象添加方法并访问对象的属性。

      bill.sayName = function() {

      console.log( "Hello " + this.name );

      };

      bill.sayName(); 

    在方法中可以通过this.propertyName来访问该对象的属性值。this所指的对象就是调用该方法的对象。这个和java一样。

     

     

  • 相关阅读:
    Mysql任务调度
    使用 IntraWeb (18)
    使用 IntraWeb (17)
    替盛大代发的招聘启示
    使用 IntraWeb (16)
    使用 IntraWeb (15)
    使用 IntraWeb (14)
    使用 IntraWeb (13)
    使用 IntraWeb (12)
    使用 IntraWeb (11)
  • 原文地址:https://www.cnblogs.com/hjy9420/p/4950242.html
Copyright © 2011-2022 走看看