千家信息网

Objects创建对象的方式有哪些

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,本篇内容介绍了"Objects创建对象的方式有哪些"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!Da
千家信息网最后更新 2025年02月01日Objects创建对象的方式有哪些

本篇内容介绍了"Objects创建对象的方式有哪些"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Data Structures

Data Types: numbers, strings, booleans and arrays.
Boolean
若没有设置或者设置为0,-0,null,"",false,undefined,NaN时为false,其他情况为true
Arrays

var myCars=new Array();var myCars=new Array("Saab","Volvo","BMW"); var myCars=["Saab","Volvo","BMW"];

Objects

创建对象两种方式

(1)object literal notation

var myObj = {    type: 'fancy',age:24,    speak: function(){}   //method};

(2)object constructor

var myObj = new Object(); //using a built-in constructor called ObjectmyObj["name"] = "Charlie";myObj.name = "Charlie";

自定义的构造函数

function Rabbit(adjective) {    this.adjective = adjective;    var age=12; //private 不能用this修饰    this.describeMyself = function() {        console.log("I am a " + this.adjective + " rabbit");    };}var rabbit1 = new Rabbit("fluffy");//className.prototype.newMethod = function(){} 给某个类添加方法Rabbit.prototype.describeMyself = function (){}

Object Oriented

继承

// the original Animal class and sayName methodfunction Animal(name, numLegs) {    this.name = name;    this.numLegs = numLegs;}Animal.prototype.sayName = function() {    console.log("Hi my name is " + this.name);};// define a Penguin classfunction Penguin(name) {    this.name = name;    this.numLegs = 2;}// set its prototype to be a new instance of AnimalPenguin.prototype = new Animal();var p =new Penguin("Timmy");p.sayName();

自定义声明的类都继承自Object类

//Object.prototype itself is an object// what is this "Object.prototype" anyway...?var prototypeType = typeof Object.prototype;console.log(prototypeType); //object// now let's examine it!var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");console.log(hasOwn); //true

私有化成员和方法

/*Public properties can be accessed from outside the classPrivate properties can only be accessed from within the class*/function Person(first,last,age) {   this.firstname = first;   this.lastname = last;   this.age = age;   var bankBalance = 7500;  //var this.bankBalance  (不能加this)     var returnBalance = function() {      return bankBalance;   };         // create the new function here   this.askTeller = function (){        return returnBalance;    }}var john = new Person('John','Smith',30);console.log(john.returnBalance);var myBalanceMethod = john.askTeller();var myBalance = myBalanceMethod();console.log(myBalance);

"Objects创建对象的方式有哪些"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0