本篇内容介绍了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。