日期:2014-05-16 浏览次数:20433 次
//or var dog = {}; //or var dog = new MyDogType(); var dog = new Object(); dog.name = "Scooby"; dog.owner = {}; dog.owner.name = "Mike"; dog.bark = function () { return "Woof"; }; console.log(dog.name); // Scooby console.log(dog.owner.name); // Mike console.log(dog.bark()); // Woof
var dog = { name: "Scooby?", owner: { name: "Mike" }, bark: function () { return" Woof"; } }; console.log(dog.name); // Scooby console.log(dog.owner.name); // Mike console.log(dog.bark()); // Woof
function Customer() { // private field var risk = 0; this.getRisk = function () { return risk; }; this.setRisk = function (newRisk) { risk = newRisk; }; this.checkRisk = function () { if (risk > 1000) return" Risk Warning"; return" No Risk"; }; } Customer.prototype.addOrder = function (orderAmount) { this.setRisk(orderAmount + this.getRisk()); return this.getRisk(); }; var customer = new Customer(); console.log(customer.getRisk()); // 0 console.log(customer.addOrder(2000)); // 2000 console.log(customer.checkRisk()); // Risk Warning
function Customer(name) { var that = this; var risk = 0; this.name = name; this.type = findType(); // private method function findType() { console.log(that.name); console.log(risk); return" GOLD"; } }
function Customer(name) { var that = this; var risk = 0; this.name = name; // private method var findType = function () { console.log(that.name); console.log(risk); return" GOLD"; }; this.type = findType(); } var customer = new Customer("ABC Customer"); // ABC Customer // 0 console.log(customer.type); // GOLD console.log(customer.risk); // undefined
function Outer() { return new Inner(); //private inner function Inner() { this.sayHello = function () { console.log('Hello'); } } } (new Outer()).sayHello(); // Hello
function Customer(orderAmount) { // private field var cost = orderAmount / 2; this.orderAmount = orderAmount; var that = this; // privileged method this.calculateProfit = function () { return that.orderAmount - cost; }; } Customer.prototype.report = function () { console.log(this.calculateProfit()); }; var customer = new Customer(3000); customer.report(); // 1500
function Customer(name, orderAmount) { // public fields this.name = name; this.orderAmount = orderAmount; } Customer.prototype.type = "NORMAL"; Customer.prototype.report = function () { console.log(this.name); console.log(this.orderAmount); console.log(this.type); console.log(this.country); }; Customer.prototype.promoteType = function () { this.type = "SILVER"; }; var customer1 = new Customer("Customer 1", 10); // public field customer1.country = "A Country"; customer1.report