js基本语法老师只讲了一天, 最悲伤的事情就是书写习惯好难改变,
请各位读者在阅读我的代码时,自己脑补一下分号,python敲的多了。。
总是会忘记添加分号,每次都是自己后来一行一行的添加,很想知道各位
大佬都是怎么区分的。
js创建对象的两种方法:
第一种:字面量语法
//在对象里面,变量即对象的属性,函数即对象的方法
var flower = {}
flower.name = 'lily'
flower.price = 30
flower.num = 3
flower.totalPrices = {
function(){
return this.price *this.num
}
}
//设置属性时向对待变量一样对待属性
/*
访问属性或方法时使用点符号,也可以使用方括号,方括号可以用来访问对象的属性,但不可以用来访问方法
eg:
var flowerName = flower.name;
var flowerPrices = flower.totalPrices;
var flowerName = flower['name']
*/
第二种:对象构造函数语法
//创建单个对象
var flower = new Object()
flower.name = 'lily'
flower.price = 30
flower.num = 3
flower.totalPrices = function(){
return this.price *this.num
}
/*
一旦创建一个对象,添加或者删除属性的方法都是相同的,如果对象是用构造函数创建的,
操作时仅仅添加或者移除对象的某个实例的属性,而并非该对象
*/
//创建多个对象,使用构造函数
function Flower(name,price,num){
this.name = name //this关键字表示,使用的是当前对象的属性
this.price = price
this.num = num
this.totalPrices = function(){
return this.price *this.num;
};
}
var flower1 = new Flower('lily',30,3)
var flower1 = new Flower('rose',45,9)