您好,登錄后才能下訂單哦!
本篇內容介紹了“Objects創建對象的方式有哪些”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
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 Object myObj["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 (){}
繼承
// 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();
自定義聲明的類都繼承自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 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創建對象的方式有哪些”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。