Javascript 有两种类型的属性和方法。您可以使用静态和实例两种类型的属性和方法。
首先您需要知道如何在 javascript 中定义对象。两种主要方式是使用 {} 或使用构造函数。在 {} 中,每个属性和方法都是静态的,您不能创建它的实例,例如:
<script>
var person = {name:"Chayon Shaah",age:"30",say:function(){return "Hello "+this.name}}
alert(person.say()); // will allert "Hello Chayon Shaah"
</script>
只看代码,这里你需要通过对象引用来调用任何属性或方法,并且不能使用new关键字创建这个人对象的任何实例
现在看看构造函数,它是如何创建实例的:
<script>
function Person(){
this.name="Chayon Shaah",
this.age = 30,
this.say = function(){
return "Hello "+this.name;
}
}
var obj = new Person();
alert(obj.say()); // will alert "Hello Chayon Shaah"
</script>
这里所有的Person对象属性和方法都可以被“obj”访问,它是Person对象的一个实例。
Person 对象不能直接访问它们,只有它的任何实例可以访问它们。另一方面,您可以对 Person 对象使用静态属性或方法,该对象只能通过其自身而不是其任何实例进行访问。
让我们在 Person 对象中添加更多实例属性和静态属性...
<script>
function Person(){
this.name="Chayon Shaah",
this.age = 30,
this.say = function(){
return "Hello "+this.name;
}
}
var obj = new Person();
alert(obj.say());
Person.prototype.city = "Mymensingh"; // only can be used by all instances of Person object (non static property).
alert(obj.city); // Will alert "Mymensing" (Calling via instance of Person)
Person.location = "Bangladesh"; //This is a static property which can not be accessed by any instance of Person object, Only accessed by Person Object.
`alert(Person.location); // Will alert "Bangladesh" (Calling directly via` Person object)
</script>
使用“prototype”关键字创建任何实例方法或具有主对象名称的属性,如果您想创建静态属性和方法,则只需使用名称而不使用“prototype”关键字,如示例。
我认为它会帮助你......