您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Objects創(chuàng)建對(duì)象的方式有哪些”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
Data Types: numbers, strings, booleans and arrays.
Boolean
若沒有設(shè)置或者設(shè)置為0,-0,null,"",false,undefined,NaN時(shí)為false,其他情況為true
Arrays
var myCars=new Array(); var myCars=new Array("Saab","Volvo","BMW"); var myCars=["Saab","Volvo","BMW"];
Objects
創(chuàng)建對(duì)象兩種方式
(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 Object myObj["name"] = "Charlie"; myObj.name = "Charlie";
自定義的構(gòu)造函數(shù)
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(){} 給某個(gè)類添加方法 Rabbit.prototype.describeMyself = function (){}
繼承
// the original Animal class and sayName method function Animal(name, numLegs) { this.name = name; this.numLegs = numLegs; } Animal.prototype.sayName = function() { console.log("Hi my name is " + this.name); }; // define a Penguin class function Penguin(name) { this.name = name; this.numLegs = 2; } // set its prototype to be a new instance of Animal Penguin.prototype = new Animal(); var p =new Penguin("Timmy"); p.sayName();
自定義聲明的類都繼承自O(shè)bject類
//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 class Private 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創(chuàng)建對(duì)象的方式有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。