JS class concept
Class, which is essentially a function, is also a constructor for that class, new creates instances of that class, and new produces objects that have properties and methods. Methods are also a special kind of object.
Methods of a class
Initializing an instance in a constructor (that is, writing the method directly in the constructor and new instantiating it) is not recommended and consumes memory (each time the instantiation is repeated, taking up more memory is neither environmentally friendly nor efficient). All instances are common. Creating multiple instances does not create new functions. It is recommended to define the prototype method of the instance, which is common to all instances.
1. Encapsulate classes like jQuery
Anonymous functions
(function () {
//
})();
var Id = function (i) {
this.id = document.getElementById(i);
};
window.$ = function (i) {
return new Id(i);
};
console.log($('main'));
Copy the code
function Cat(name, color) { this.name = name; this.color = color; } var cat1 = new Cat(' Cat ', 'yellow '); Var cat2 = new Cat(' 2 ', 'black '); Cat.prototype.a = 'aaa'; Cat.prototype.type = 'Cat '; Cat.prototype. Eat = function () {alert(' eat '); }; cat1.eat(); cat2.eat(); console.log(cat1.name); console.log(cat2.color); Cat1 and cat2 automatically have a constructor attribute pointing to their constructors. console.log(cat1.constructor == Cat); console.log(cat2.constructor == Cat); // Javascript also provides an instanceof operator to verify the relationship between prototype objects and instance objects. console.log(cat1 instanceof Cat); try { console.log(a instanceof Cat); } catch (e) { console.log(e); }Copy the code
The “constructor” is just a normal function, but it uses the this variable inside. Using the new operator on the constructor generates the instance, and the this variable is bound to the instance object. Javascript states that each constructor has a Prototype property that points to another object. All properties and methods of this object are inherited by instances of the constructor.
1. IsPrototypeOf () checks the relationship between a Prototype object and an instance 2. HasOwnProperty () checks whether a property is local or inherited from a Prototype object 3 Determine if it is in an object
function Cat(name, color) { this.name = name; this.color = color; } cat.prototype. type = 'Cat '; Var cat1 = new Cat(' Cat ', 'yellow '); Var cat2 = new Cat(' 2 ', 'black '); console.log(Cat.prototype.isPrototypeOf(cat1)); console.log(Cat.prototype.isPrototypeOf(cat2)); console.log(cat1.hasOwnProperty('name')); console.log(cat2.hasOwnProperty('type')); console.log('name' in cat1); console.log('type' in cat1);Copy the code